In One sentence, TypeScript is a superset of JavaScript. It was developed by Microsoft in 2012.
Let's see why the TypeScript language exists in this world.
TypeScript solves some common problems of JavaScript by adding some additional features on top of the JavaScript language.
We know that Javascript is a dynamically typed language. For this, we don't need to think about data types while writing code. But there is some problem.
Look at the below code snippet to understand the problem.
const add = (a) => (b) => a + b;
add(1)(2) // 3 (expected result)
add(1)('2') // '12' (unexpected result and no error)
We can see that when we pass two numbers to the add function it gives us a return value which is number as expected. But when we pass a string and a number it gives us another string as a return value which we are not expecting.
To fix this kind of problem TypeScript implemented the feature of statically typed language in JavaScript. Let's see the above example in typescript.
const add: (a: number) => (b: number) => number =
(a) => (b) => a + b
console.log(add(1)(2)) // 3 (expected)
console.log(add(1)('2')) // Error --> Argument of type 'string' is not assignable to parameter of type 'number'.
In the add function, we have defined that parameters a and b will be number. So when we pass two numbers we get our expected result. But when we pass a number and a string TypeScript compiler gives us an error. In modern IDE, the error will be shown instantly after writing the line. You don't need to compile it to catch this kind of error.
Does TypeScript replace JavaScript?
The answer is no. As browsers still don't understand the TypeScript language, we have to compile our TypeScript code to JavaScript for making the code workable.
We have seen what typescript is in short. But it has some huge topics to explore. Check their official documentation to know more.
There is also a playground to play with the typescript language.
Top comments (0)