TypeScript is the new kid in town. Angular, Ionic and React developers are using it.
- It brings types to the table
I still remember the good old times as Java Developer repetitively typing:
Don’t worry about that, the typings are only here to help.
The main types are boolean, number, string, array, any and void.
Nothing new here.
any is quite useful if you are not sure which type of objects you will have to handle so use it with moderation.
On the function side, the arguments can also be typed alongside the returned value:
And if the function doesn’t return anything, void is our friend:
TypeScript generally uses ES6 feature, in case you missed it, here is a fat arrow method:
Moving on the Interface aka: The Contract.
Interfaces literally tell developers to use them in a specific way or not to use them at all.
Implementing an Interface is signing a contract saying that the properties’ types will be respected and each method will be created.
You can’t grab an Interface and use it as you want.
Here is the creation of an Interface:
And it’s implementation:
Finally the Classes.
Very similar to ES6 Classes, but more information can be added.
We can now create Accessors and limit our scope:
We have here a private property, which is only accessible through getters and setters.
This is just for knowledge, I’m not a big fan of this syntax and it’s against Angular’s guidelines:
Avoid prefixing private properties and methods with an underscore.
Finally the Generics.
This can be quite touchy, I first discovered this concept eight years ago with JAVA.
Generics allows us to set types on the fly.
If we don’t know an argument’s type we generally use any. By doing this, we lose the type of the argument, which can be an issue in certain cases.
The following code allows us to pass any type we want, as long as we specify the type when creating the object:
The person object is expecting a string whereas the person2 object is expecting a number.
Inside the sayHi method, the word variable will be a string for person and a number for person2.
It might take some time, but you will see that TypeScript is an improvement. Generally you discover its true power when coding with a real IDE and the errors are appearing in real-time as you are coding.
This also comes with another update called Intellisense, thanks to the typings and Interfaces, people generally document everything and this documentation is displayed as you type:
Finally, using access specifiers can add some robustness to the code.
All of that is totally optional, you take what you like and totally ignore what doesn’t look interesting for you.