The Problem Types Solve

What TypeScript is. JavaScript with type annotations, checked before the code runs and then removed.

Nothing survives into the output but the JavaScript you already know how to write. Types cost nothing at runtime, and they provide nothing at runtime either. Both halves of that sentence matter, and the second half is where most real TypeScript bugs come from.

The same bug, two moments

JavaScript

// JavaScript: fine until it runs
function total(prices) {
  return prices.reduce(
    (a, b) => a + b, 0
  );
}

total("12");
// runs, returns "012"

TypeScript

// TypeScript: rejected now
function total(
  prices: number[]
): number {
  return prices.reduce(
    (a, b) => a + b, 0
  );
}

total("12");
// error, before running
Compare → The JavaScript version does not crash. It quietly returns the string "012", which then flows into whatever uses it. That is the bug type systems are actually good at: not crashes, but wrong answers that look plausible.

Try it

Remove the last line and watch the error clear. Then change the annotation to string[] and see the error move to the line above.

loading editor…

checking…

The real compiler, in strict mode. The error below is tsc's own message, exactly as you would see it in an editor.

What it does not do

TypeScript catches shape mistakes, not logic mistakes. A function that returns the wrong number still returns a number, and the compiler is satisfied. It is a tool for one class of error, and it is very good at that class.

Mark this lesson complete

Your progress is saved on this device. No account needed.

Next: What It Costs
← Back