Member-only story
What is TypeScript
You might have seen this type of code if you are a JavaScript programmer.
function add(num1, num2) {
return num1 + num2;
}
This allows you to add 2 numbers and return the result. Well not quite. It will try to apply the + operation on these two variables regardless of the values they possess.
E.g.
add(1,2) // This will give 3
add('1', '2') // This will give '12'
Mmm. That means we should only pass numbers if we expect an additional operation to be performed. But how do we make that possible? That is why we need types.
Here is the function refactored with types —
function add(num1: number, num2: number): number {
return num1 + num2;
}
And now if you try to call the function as so —
add(1,2); // gives 3 as usual
add('1', '2'); // gives error
/**
Argument of type 'string' is not assignable
to parameter of type 'number'.ts(2345)
**/
It starts throwing an error since the TS compiler now tells you that — “hey I am expecting only numbers to be passed. Can you check that again?”
And that is what TypeScript aims to solve.
Superset
TypeScript is a superset of JavaScript. It has everything that JS has and adds types to it. Your JS got even better to be precise.
But TS is not exactly a language that can be processed by browsers. The browsers…