As we saw in the first entry of this series why is important to consider TypeScript in your development, we are going to check the features needed to understand how this JavaScript superset works. In this entry we are going to learn what are the most basic types in TypeScript, which they are:
- Boolean
- Number
- String
- Array
- Any
- and many more...
Booleans
This is the most basic type which is onlt two values possible: true
or false
. How to declare a boolean type? Pretty ease actually:
let myFlag: boolean = true
// After doing this you can make all the usual uses for a boolean variable, with the only difference that you can't redeclare the type value as we saw before.
myFlag = 'true'
// TypeSciprt will alert that this is impossible because myFlag is a boolean type and not an string type
Number
As the name says, this is a number type that can assign: integers, floating point, hexadecimal, decimal, octal and binaries values. By assigning the number type, if you are using VS Code you can access into all the functions and methods available to the number type thanks to the Intellisense feature.
String
String types are the usual variables to use a paragraph, URL, etc, values given into our variable. We can set an string type by using '
, ""
and string literals. Which the string template we can use variables inside as we usually do in JavaScript (a demostration that TypeScript is still JavaScript).
Array
Arrays are a particular case in TypeScript because there two ways to declare an array variable. To set this type we need have to
// We can set this variable like this:
const myArray: number[] = []
or
const myArray: Array<number> = []
And we can access all the functions available for the array type:
This particular type is special because if we declare an array of type as we can see at the previous example, we can't add another value type into the array, and if you try, Intellisense will alert you that is forbidden:
Any
This is a very special type because this one can make all the previous types available, like if were using normal JavaScript. We can set a number type and later change it into a boolean type and so on, so be careful to use this type because this one release one of the security features from TS. Also, if you set an array of any types you can add wharever you want into the array without any restriction.
As we can see, the Intellisense from VSCode didn't alert me by changing the value of an any var, of by adding any var type into the array.
Conclusion
As we saw in this post, declaring a type isn't hard to do and is a helpful feature within the development. In my personal point of view this can saves you from doing a mistake during the development of a product. I know a professional JavaScript dev won't make that mistake but we aren't excent from doing a mistake, so if we can have this can of help, is a welcome one. I invite you to join into TypeScript, you will enjoy learning this beautiful JavaScript super power.
Top comments (0)