TypeScript introduction
Every programming language has built-in data types. These types tell the programming language what kind of data it is and what it can do with it.
For example:
- When you want to calculate something, you need a number (42).
- When you want to write some text on the screen, you need a string ('Hello World!').
- When you want to decide whether to do something or not, you need a boolean (true or false).
Many programming languages require you as a developer to write down the data-type when you declare a variable. These languages, for example Java, are 'strongly typed'.
String name = "John";
JavaScript is a loosely typed language. When you write and run your code, JavaScript will look at your code and figure out which data-type you meant.
const answer = 42; // JavaScript knows it is a number
const name = 'John'; // JavaScript knows it is a string
const isAmazing = true; // JavaScript knows it is a boolean
This loose typing might seem nice. You don't have to write every type because JavaScript will figure it out for you. But it can cause many problems and bugs when your application grows in complexity. Let's look at a simple example.
function add(n1, n2) {
return n1 + n2;
}
const result = add(2, 4); // result is 6
const weirdResult = add('2', 4); // weirdResult is 24
In the example above the weirdResult is 24 because we try to add a string '2' to a number 4. Because this is not possible JavaScript tries to be helpful. It changes the datatype of the number 4 to the string '4' and then adds the strings together, resulting in the string '24'. These kind of bugs are hard to find and fix.
Because these problems are so common Microsoft created TypeScript. TypeScript is a 'superset' of JavaScript. This means that it is JavaScript plus types. It can help fix the previous example by making it explicit that this function should only receive numbers. When you then try to give the function the wrong parameter types it gives you an early warning and error, preventing you from making that mistake.
function add(n1: number, n2: number) {
return n1 + n2;
}
const result = add(2, 4); // result is 6
const weirdResult = add('2', 4); // TYPESCRIPT ERROR!!!
Applications written in TypeScript are:
- More reliable
- Easier to understand
- Easier to refactor
Learning TypeScript might take you a bit of extra time to learn but it is worth the investment. So let's get started.
Further reading
- For more information about TypeScript you can check their docs: https://www.typescriptlang.org/