Lesson 34 of 50TypeScript
Why TypeScript
See what TypeScript adds to JavaScript, how it compiles away, and why most new JS codebases now use it.
You have now seen JavaScript from its first values to the toolchain a team runs it in. The last unit adds types on top of everything you know. Most JavaScript bugs that reach users are boring: a property that is undefined, a string where a number should be, a function called with its arguments in the wrong order. TypeScript catches that whole family of bugs while you type, before the code ever runs. It is the default for new React, Next.js and Node.js projects, and most JavaScript job listings now expect it.
A typed superset of JavaScript
TypeScript is JavaScript plus type annotations: little labels that say what kind of value a variable, parameter or return value holds. Every JavaScript program is already (almost always) a valid TypeScript program. You add types on top, where they help.
function cartTotal(priceCents: number, quantity: number): number {
return priceCents * quantity;
}The : number parts are the annotations. priceCents must be a number, quantity must be a number, and the function promises to return a number. That is the whole idea. Everything else in this unit is a richer way of describing values.
A superset means TypeScript adds to JavaScript without changing how it runs. There is no TypeScript runtime and no TypeScript-only standard library. The reduce, map and fetch you already know are the same functions.
Press Run (⌘ Enter) to see what happens.type Item = ... gives a name to the shape of an object. Item[] means "an array of Item". Run it, then try changing qty: 2 to qty: "2". The code still runs here (more on why in a moment), but in a real editor that line turns red instantly.
2012
TypeScript 0.8
Microsoft releases TypeScript, designed by Anders Hejlsberg (who also designed C#), to make large JavaScript apps manageable.
2016
TypeScript 2.0
Adds `strictNullChecks`, so `null` and `undefined` stop sneaking into every type.
2016
Angular 2 and VS Code
Angular is rewritten in TypeScript, and VS Code (itself written in TypeScript) uses it to power JavaScript autocomplete.
2020s
The default
Create React App gives way to Vite and Next.js, which scaffold TypeScript by default. Deno and Bun run `.ts` files directly.
2025
Node strips types
Node.js can run `.ts` files by erasing the types, and the compiler is being ported to Go for roughly 10x faster checks.
Catching bugs before runtime
Here is a real bug class. A price comes from a form field, and form fields are always strings.
Press Run (⌘ Enter) to see what happens.What does this print?
function addTax(price) {
return price + price * 0.2;
}
console.log(addTax("10"));JavaScript did not complain. It happily produced "102". With one annotation, TypeScript refuses to compile the bad call:
function addTax(price: number): number {
return price + price * 0.2;
}
addTax("10");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.Typos get the same treatment:
type User = { name: string; email: string };
const user: User = { name: "Ada", email: "ada@example.com" };
sendWelcome(user.emial);
// Error: Property 'emial' does not exist on type 'User'. Did you mean 'email'?addTax("10") error show up in a TypeScript project?Structural typing: shapes, not names
TypeScript compares types by their shape (which properties, of which types), not by their name. This is called structural typing. If a value has everything a type asks for, it fits, even if nobody declared it as that type.
Press Run (⌘ Enter) to see what happens.city was never declared as a Point. It has an extra name. It still fits, because it has a numeric x and y. This matches how JavaScript code is actually written: objects are passed around by what they contain. Languages like Java and C# use nominal typing instead, where the declared class name has to match.
class Cat { name = "Tom"; speak() { return "meow"; } }
class Robot { name = "R2"; speak() { return "beep"; } }
const pet: Cat = new Robot();tsc and type erasure
The TypeScript compiler, tsc, does two separate jobs:
- Type check: read every file and report errors.
- Emit: write plain JavaScript by deleting the type annotations.
You write .ts files with annotations.
type Item = { priceCents: number; qty: number };
export function lineTotal(item: Item): number {
return item.priceCents * item.qty;
}export function lineTotal(item) {
return item.priceCents * item.qty;
}npm install --save-dev typescriptnpx tsc --init # creates tsconfig.jsonnpx tsc # check and emitnpx tsc --noEmit # check only (common in Vite and Next.js projects)This is called type erasure: types are a compile-time tool and vanish completely. That has a big consequence. TypeScript cannot check data it never sees, such as a JSON response.
What does this print?
type User = { name: string };
const data: User = JSON.parse('{"name": 42}');
console.log(typeof data.name);Editor tooling
The type checker also runs inside your editor as a language service. That is what gives you:
- Autocomplete that knows every property of every object.
- Red squiggles on mistakes, with the error message on hover.
- Go to definition, find all references, and rename symbol across hundreds of files safely.
- Quick fixes like "add missing import" or "add missing property".
Even plain .js files in VS Code get autocomplete from TypeScript under the hood. Renaming a function used in 40 files takes one keystroke instead of a nervous find-and-replace.
The cost and the payoff
TypeScript is not free. You learn a second language layered on the first, you add a check step to the build, and occasionally you fight the type checker over code you know is correct.
| Costs | Payoff |
|---|---|
| A learning curve (this unit) | Whole classes of bugs found before running |
A check step (tsc --noEmit) in CI | Safe refactors across a big codebase |
| Some extra syntax | Types act as documentation that cannot go stale |
| Typing awkward library code | Autocomplete for every API you call |
For anything beyond a small script, teams overwhelmingly find the trade worth it. Developer surveys (Stack Overflow, State of JS) consistently show TypeScript as one of the most used and most liked languages, and frameworks like Next.js, Angular, NestJS and Astro are written in it.
Match each problem to what catches it.
Format a price in cents
Shops store money as whole cents (1250), never as floats (12.5), because floats cannot represent most decimal fractions exactly. Write formatPrice(cents: number): string that turns cents into a dollar string with exactly two decimal places.
formatPrice(1250) → "$12.50"
formatPrice(5) → "$0.05"
formatPrice(-305) → "-$3.05"The minus sign goes before the dollar sign. No thousands separators. You can assume cents is an integer.
- TypeScript
- A typed superset of JavaScript. You add type annotations, and the compiler checks them and emits plain JavaScript.
- type annotation
- A label like
: numberthat states what type a variable, parameter or return value has. - structural typing
- Types are compatible when their shapes match (same properties and types), regardless of their names.
- type erasure
- Compiling removes all types. At runtime only plain JavaScript exists, so types cannot check live data.
- tsc
- The TypeScript compiler. It type-checks your project and can emit JavaScript, or only check with
--noEmit.