Lessons · TypeScript · what TypeScript adds
Types, checked before it runs
TypeScript adds types that are checked when you compile and erased when you run. The browser runs plain JavaScript; the mistakes were caught before it got there.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
A wrong argument, a misspelled property, a null nobody handled: in JavaScript these crash for a user; in TypeScript they are red underlines for the author.
How to think about it
Annotate the edges (function parameters, return types, data from outside) and let inference handle the middle. Every error the compiler shows is a runtime bug you did not ship.
Worked example
function box(w: number, h: number): number { return w * h; }Types say what goes in and what comes out.box(2, 3);Fine.
box("2", 3);Error: a string where a number was promised, caught before the code runs.Your turn
Type the list of prices.
function total(prices: []): number { return prices.reduce((a, b) => a + b, 0); }Solve one with the compiler running
The trap
TypeScript checks what you tell it. A value from fetch typed as any stays unchecked, and the crash moves back to runtime.