Typescript: Quick Tutorial
Installation
Compilation
Tsconfig - strict typing
If we run command above, tsconfig.json
will be created, by default with "strict": true
. Enabling strict mode means, that typescript will warn us for example if something can be null.
If we have tsconfig.json
file under our project, then we compile only with tsc
command.
Static Typing
A very distinctive feature of TypeScript is the support of static typing. This means that you can declare the types of variables, and the compiler will make sure that they aren’t assigned the wrong types of values. If type declarations are omitted, they will be inferred automatically from your code.
Here is an example. Any variable, function argument or return value can have its type defined on initialization:
Interfaces
Interfaces are used to type-check whether an object fits a certain structure. By defining an interface we can name a specific combination of variables, making sure that they will always go together. When translated to JavaScript, interfaces disappear - their only purpose is to help in the development stage.
In the below example we define a simple interface to type-check a function’s arguments:
Classes
When building large scale apps, the object oriented style of programming is preferred by many developers, most notably in languages such as Java or C#. TypeScript offers a class system that is very similar to the one in these languages, including inheritance, abstract classes, interface implementations, setters/getters, and more.
It’s also fair to mention that since the most recent JavaScript update (ECMAScript 2015), classes are native to vanilla JS and can be used without TypeScript. The two implementation are very similar but have their differences, TypeScript being a bit more strict.
Continuing with the food theme, here is a simple TypeScript class:
Generics
Generics are templates that allow the same function to accept arguments of various different types. Creating reusable components using generics is better than using the any data type, as generics preserve the types of the variables that go in and out of them.
A quick example would be a script that receives an argument and returns an array containing that same argument.
The first time we called the function we manually set the type to string. This isn’t required as the compiler can see what argument has been passed and automatically decide what type suits it best, like in the second call. Although it’s not mandatory, providing the type every time is considered good practice as the compiler might fail to guess the right type in more complex scenarios.