TypeScript Introduction
TypeScript is a programming language that adds types to JavaScript.
What is TypeScript?
- TypeScript is a superset of JavaScript: every valid JavaScript program is also valid TypeScript
- It adds static types, so you can say what kind of value a variable holds
- It is compiled (turned) into plain JavaScript before it runs
- It was created by Microsoft and released in 2012, and it is free and open source
TypeScript files use the .ts extension instead of .js.
The Problem TypeScript Solves
JavaScript lets any variable hold any type. That is flexible, but mistakes only show up when the code runs, sometimes in front of a customer.
Example
// plain JavaScript
function applyDiscount(price, percent) {
return price - price * percent / 100;
}
console.log(applyDiscount("2000", 10));1800
Here the price was a string by mistake. JavaScript quietly converted it, so this time the answer looks right. But if the same mistake reaches an addition, "2000" + 150 gives "2000150", and the bug is hard to find.
The Same Code in TypeScript
Example
function applyDiscount(price: number, percent: number): number {
return price - price * percent / 100;
}
console.log(applyDiscount(2000, 10));
applyDiscount("2000", 10);error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
TypeScript stops you before the code runs, and your editor underlines the mistake in red.
Static vs Dynamic Typing
| JavaScript | TypeScript | |
|---|---|---|
| Typing | Dynamic: checked while running | Static: checked before running |
| File extension | .js | .ts (and .tsx for React) |
| Runs in the browser directly | Yes | No, compiled to JavaScript first |
| Type errors found | At runtime | While writing and compiling |
| Editor help | Basic | Smart autocomplete and error hints |
Type Inference
You do not have to write a type everywhere. TypeScript infers (works out) the type from the value:
Example
let city = "Karachi"; // TypeScript knows this is a string
city = 42; // Error: Type 'number' is not assignable to type 'string'Where is TypeScript Used?
- Front-end frameworks: Angular is written in TypeScript, and most React and Vue projects use it
- Back-end servers with Node.js, Express and NestJS
- Full stack frameworks like Next.js
- Desktop apps like Visual Studio Code, which is itself written in TypeScript
TypeScript types only exist while you write and compile the code. They are removed in the final JavaScript, so they do not make your website slower.
Exercise
Exercise
Which statement about TypeScript is true?
