Skip to content

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.

12 min read0/6 questions

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.

TypeScript
type Item = { name: string; priceCents: number; qty: number }; function cartTotal(items: Item[]): number { return items.reduce((sum, item) => sum + item.priceCents * item.qty, 0);} const cart: Item[] = [ { name: "Notebook", priceCents: 450, qty: 2 }, { name: "Pen", priceCents: 120, qty: 3 },]; console.log(cartTotal(cart));
Output
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.

Where TypeScript came from
  1. 2012

    TypeScript 0.8

    Microsoft releases TypeScript, designed by Anders Hejlsberg (who also designed C#), to make large JavaScript apps manageable.

  2. 2016

    TypeScript 2.0

    Adds `strictNullChecks`, so `null` and `undefined` stop sneaking into every type.

  3. 2016

    Angular 2 and VS Code

    Angular is rewritten in TypeScript, and VS Code (itself written in TypeScript) uses it to power JavaScript autocomplete.

  4. 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.

  5. 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.

JavaScript
function addTax(price) { return price + price * 0.2;} console.log(addTax(10));console.log(addTax("10"));
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputJavaScript

What does this print?

function addTax(price) {
return price + price * 0.2;
}
console.log(addTax("10"));
Need a nudge? Hints walk you through it.

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'?
Quick check
When does the addTax("10") error show up in a TypeScript project?
Need a nudge? A hint rules out a wrong answer.

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.

TypeScript
type Point = { x: number; y: number }; function distanceFromOrigin(p: Point): number { return Math.sqrt(p.x ** 2 + p.y ** 2);} const city = { name: "Oslo", x: 3, y: 4 };console.log(distanceFromOrigin(city));
Output
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.

Quick check
Does this compile?
class Cat { name = "Tom"; speak() { return "meow"; } }
class Robot { name = "R2"; speak() { return "beep"; } }

const pet: Cat = new Robot();
Need a nudge? A hint rules out a wrong answer.

tsc and type erasure

The TypeScript compiler, tsc, does two separate jobs:

  1. Type check: read every file and report errors.
  2. Emit: write plain JavaScript by deleting the type annotations.
From .ts to running code
cart.ts: your code + typescart.tsyour code + typestsc: check + striptsccheck + stripErrors: editor, CIErrorseditor, CIcart.js: plain JavaScriptcart.jsplain JavaScriptBrowser / Node: never sees typesBrowser / Nodenever sees typescompilereportemitrun

You write .ts files with annotations.

1/4
type Item = { priceCents: number; qty: number };
 
export function lineTotal(item: Item): number {
  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.

Predict the outputTypeScript

What does this print?

type User = { name: string };

const data: User = JSON.parse('{"name": 42}');
console.log(typeof data.name);
Need a nudge? Hints walk you through it.
Quick check
Which of these still exists when the JavaScript runs?
Need a nudge? A hint rules out a wrong answer.

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.

CostsPayoff
A learning curve (this unit)Whole classes of bugs found before running
A check step (tsc --noEmit) in CISafe refactors across a big codebase
Some extra syntaxTypes act as documentation that cannot go stale
Typing awkward library codeAutocomplete 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 the pairs0/4 matched

Match each problem to what catches it.

Choose an item, then its match on the other side.
ChallengeEasy

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
function formatPrice(cents: number): string { // Split into whole dollars and leftover cents, then pad the cents to 2 digits. return "";}
Key terms
TypeScript
A typed superset of JavaScript. You add type annotations, and the compiler checks them and emits plain JavaScript.
type annotation
A label like : number that 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.