I have recently been creating an app using Angular 2, the latest version of the framework. Google have totally rewritten the framework from the ground up and one of the big changes is the use of TypeScript. It’s worth noting at this point that you don’t need to use TypeScript with Angular 2, but it’s recommended and the docs are primarily written with TypeScript.
So let’s dive straight into an example of how to use types with TypeScript.
The above code is saying that any value assigned to the myString variable must always be a string. And when compiled this would give no errors and leave you with:
So what happens if we break the rules?
This time I have assigned the number 10 to the myString variable. When I try and compile this code I will get the following error:
error TS2322: Type 'number' is not assignable to type 'string'. TypeScript has seen that I am trying to assign a number to a variable that must be a string, so it fails the compilation.
In the example above I explicitly set a type to the variable. But this isn’t the only way to do it in TypeScript. Setting the variable to a value will infer a type, so if you try to reassign the variable with a different type, you will get an error.
So when compiling the above code, TypeScript will know that
myString is a string type.
Which means, the same as earlier, this code with give you an error.
TypeScript has a variety of different types you can assign to your variables.
In TypeScript an interface is basically a blueprint for an object. Properties with their types are passed into an interface to ensure the object will only accept the types we need it to. If a property is optional for your object, you can declare that with a question mark.
The above code will compile as the assigned values match the types. But this code will error as the password is passed in as a number:
You can also define functions in an interface. You don’t need to include the function body, as this is just a blueprint, but you can define the type of the parameters, and if the function has a return value.
that’s the basics covered
Obviously, TypeScript has a lot more to offer than I have covered in this post, but I hope to have helped you on your way to learning this great tool. If you have any other great tips for TypeScript basics, then let us know in the comments!
If you enjoyed the read, drop us a comment below or share the article, follow us on Twitter or subscribe to our #MetaBeers newsletter. Before you go, grab a PDF of the article, and let us know if it’s time we worked together.