TypeScript is a popular extension of JavaScript. Microsoft developed TypeScript as a way to reduce common errors in JavaScript programming. These benefits have seen achieve widespread adoption in many web projects.
TypeScript is a superset of JavaScript: it adds features to eliminate some of the most common complaints about the language. Because TypeScript is a superset of JavaScript, every JavaScript program is already a TypeScript program. You can rename all your .js
files into .ts
files and then claim you have a TypeScript project!
The benefits of TypeScript come from adding type annotations to code.
For example, in ordinary JavaScript, this is legal code even though it does not make sense to add $7.50 in shipping fees to the string 'Hello'
:
function addShippingFees(total) {
return total + 7.5; // Shipping costs $7.50
}
// This doesn't make sense, but it is valid JavaScript
addShippingFees('Hello');
TypeScript lets developers add type annotations to help detect common problems. In the following code, TypeScript will report a compile error (Argument of type '"Hello"' is not assignable to parameter of type 'number'.):
function addShippingFees(total : number) {
return total + 7.5; // Shipping costs $7.50
}
// TypeScript detects a problem here:
// 'Hello' is not valid: it is not a number
addShippingFees('Hello');
The type annotations create additional short-term work for developers, but they bring greater simplicity to code. Types can exclude complex interactions from the language. For example, there is less concern for the complex rules for adding strings and numbers (the +
operator) because type annotations can prevent such code from even compiling.
Newly created Angular projects use TypeScript by default. It is also possible to create a new React project using TypeScript. In fact, you can use the TypeScript compiler to replace any JavaScript code with TypeScript. The compiler translates TypeScript code into ordinary JavaScript: use the command npx tsc
after installing TypeScript (npm install typescript
).
The disadvantage to TypeScript is that it is less forgiving of errors and so less ‘beginner-friendly’ for new programmers. If you are new to JavaScript, I recommend adding types to your code with TypeScript after you feel confident in JavaScript. However, once you’ve gained confidence in JavaScript, switching to TypeScript can help uncover difficult-to-find bugs.