Lesson: Understanding TypeScript’s Types

0

TypeScript JavaScript that scales.

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:

image00

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.

image03

We can use types in functions (even constructors) as we see here:

image04

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.

image01

This type indicates that the variable can be assigned any value, which is the situation we’re used to in JavaScript. So, the something variable can be assigned the value of 3, or true, or the string “Mr. Impostor”. It can even be assigned all three values at given points of time during the execution of your application.

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:

image02

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?

The biggest names in JavaScript education, Dan Wahlin, John Papa, and Joe Eames have teamed up to deliver an invaluable learning experience. 

“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

Don’t miss the next workshop, enroll now!

You might also like More from author

Leave A Reply

Your email address will not be published.