TypeScript essentials

Narrowing, generics, discriminated unions, utility types. Product-company codebases assume it; interviews increasingly require it.

About 30 min read3-question knowledge check

The mental model

TypeScript is a **static description of the shapes your values can have**, checked before the code runs and then **erased**. That last word is the whole mental model: types exist at compile time only. At runtime there is no TypeScript — the browser runs plain JavaScript with every annotation stripped. So a type is a *promise you make to the compiler*, and the compiler's job is to prove you never break that promise anywhere in your code. It cannot prove anything about data that arrives from outside — a fetch, localStorage, a form, JSON.parse — because that data was never seen by the compiler.

The analogy that sticks: types are the *floor plan* of a building, checked by an inspector before anyone moves in. The inspector catches "this door opens into a wall" and "you can't reach the kitchen from here" — structural mistakes, before they become real. But the floor plan is not the building; on move-in day it is thrown away, and if a delivery driver hands you a box labelled "chairs" that actually contains bricks, no floor plan saved you. That box is your API response, and the discipline that saves you is validating at the boundary — checking, at runtime, that external data actually matches the type you claimed for it.

What breaks without this model is a specific and common class of production bug: the undefined is not a function and Cannot read properties of undefined errors that TypeScript was supposed to prevent, occurring precisely at the seams where untyped data enters. A developer writes const user = await res.json() as User, the API changes a field from a string to null, and the compiler — which trusted the as — said nothing, because as is a command to stop checking, not a check. Understanding that types are erased and boundaries are untyped turns TypeScript from "annotations that annoy me" into "a proof that my internal logic is consistent, plus a discipline for the edges where it isn't."

The second half of the mental model: TypeScript is **structural**, not nominal. Two types are compatible if their shapes match, regardless of their names or where they came from. An object with { name: string } satisfies any parameter typed { name: string } even if it was never declared to. This is why TypeScript feels flexible where Java feels rigid, and why "duck typing, but checked" is the accurate one-liner.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision