TypeScript: Everything You Need to Know
Introduction
What is TypeScript?
TypeScript is a statically-typed superset of JavaScript, which means the following:
- Developers can define types for variables and functions
- The static type system allows developers to catch errors during compile time instead of runtime
- As a superset to JavaScript, TypeScript adds additional syntax and features while still being compatible with existing JavaScript code.
In comparison to JavaScript, TypeScript code is compiled to JavaScript code using the TypeScript compiler. The resulting JavaScript code can then be executed on any JavaScript runtime, including browsers, Node.js, and other environments.
Why should we use TypeScript?
Let's look at this example code:
function add(num1, num2) {
return num1 + num2;
}
console.log(add('1', '2'));
Notice that we are passing string
instead of a number
. This will then result to: 12
instead of 3
.
With TypeScript, we can write it as follows:
function add(num1: number, num2: number) {
return num1 + num2;
}
// console.log(add('1', '2')); -- results to compile-time error
console.log(add(1, 2)); // prints 3