So, why should we even use TypeScript
in the first place? There are 2 main reasons we prefer it over JavaScript:
-
TypeScript
adds a type system to help you avoid many problems with dynamic types in JavaScript -
TypeScript
implements future features of JavaScript (ES Next… no idea what this is) so that we can use them today
Recall that JavaScript is dynamically types. This makes the following legal:
The variable box is capable of changing types, which makes mistakes prone:
Dynamic types can have many benefits. It makes the language very loose and flexible, allowing for some things to be done quicker and in less code. However, it introduces the risk of more error. In something like C++
, doing something like 20 + ‘allan'
would produce an error, and the code would terminate. However, in JavaScript, no error is produced, and so, the code seemingly “works”.
TypeScript
solves this issue of dynamic types. An issue that often arrises in JavaScript is calling methods that don’t exist, or calling object types, that have not yet been defined. Consider the following JavaScript code:
Two common errors are:
and
TypeScript is able to solve these issues. Essentially, instead of returning an object like that, we first sort of create a “class” or a “shape” of the object we wish to return. So, something like:
To solve the passing in arguments in the wrong order above, we can assign types:
This will show an error if we pass a number to the name argument.
Summary
- JavaScript is dynamically typed. It offers flexibility but also creates many problems.
- TypeScript adds an optional type system to JavaScript to solve these problems.