First let’s install TypeScript globally by running the following NPM command:
npm install -g typescript
Next create a new TypeScript file called
app.ts with the following function:
Here we have used type annotations to declare that the
fisrtName provided must be a
string and that the data returned from
helloWorld is a
string. Once an entity (variable, function, object…) has a type annotation declared its type cannot be changed, this ensures types remain consistent.
We can now compile our TypeScript file by running the following command:
tsc app.tsCode language: CSS (css)
This create’s a new
This has compiled as ES5 (current default) with all the TypeScript removed.
Now if we change
firstName to something other than a string, for example:
When compiled you’ll get the following error message due to the type mismatch:
Whilst you’re not required to use type annotations in TypeScript checking types helps avoid errors when dealing with different data types. They also make code more readable and easier to maintain especially in larger more complex applications.
That’s all for this tutorial. You should now have an understanding of how to compile a TypeScript file and how to use type annotations to prevent type mismatches. Thanks for reading and stay tuned for more TypeScript tutorials in the coming months.