TypeScript’s Types are really rather simple. Just look for the colon, which separates an object from its type. There are three basic types: number, string, and boolean. Creating a variable of a specific type just involves creating the identifier, then a colon, then the type as shown here:
This creates a variable “name” that is of type string. Naturally, if we try to assign 3 to it, then our TypeScript compiler will complain. It’s far more common to use this when creating properties of classes, in which case inside of a class, we simply omit the “var” from the above code to create a name property of type string as in the following code.
We can use types in functions (even constructors) as we see here:
Here, we have changed our constructor to note that the name must be a string. So, if someone tries to send in a number or a boolean as the name when constructing a Hero, TypeScript will prevent it during compilation.
There are three basic types in TypeScript: String, Boolean, and Number. With those, we can handle all of the simple types in our code.
There’s a fourth type that is very important to know: the any type.
The final commonly encountered type is the array type. Often, we need an array, but we want to constrain the values of the array to be of a specific type. For example, this is how we can create an empty array that can only contain strings with the following code:
This will mean we can only add strings to the powers array. If we try to add a number or boolean, TypeScript will prevent us.
There’s obviously more to TypeScript’s types than what little I’ve shown here, but really, this is the 20% that’ll get you 80% of the result. For further reading, I recommend you check out the TypeScript documentation at http://www.typescriptlang.org/docs/tutorial.html.
Do you want to jump start your TypeScript skills?
“Hit it out of the ballpark!” – Ed Gorski
“It was a valuable experience.” – Project Engineer, ExxonMobil
“I’m recommending this to my colleagues.” – Paul Kavanagh
“I highly recommend this course to everyone” – Yoan Pumar