TypeScript Fundamentals
Annotations, inference, interfaces, unions and narrowing: the daily TypeScript every frontend job expects.
Intermediate · about 10 hours · difficulty 3/5
Learn first: Modern JavaScript and Error Handling, JavaScript Modules
TypeScript is JavaScript plus a static type checker. The types are erased at build time, so nothing changes at runtime, but your editor and CI now catch typos, wrong arguments, missing null checks and broken refactors before users do. Most professional frontend codebases are written in it.
The essentials
- Inference first:
const count = 0is already anumber. Annotate function parameters and public APIs; let the rest be inferred. - Object shapes with
typeorinterface. Either is fine; pick one convention. - Union types:
type Status = "idle" | "loading" | "error"models real states far better than booleans. - Optional and nullable values:
name?: string,user: User | null, with optional chaininguser?.name. - Arrays, tuples and records:
string[],[number, number],Record<string, number>. - Narrowing:
typeof,in, equality checks and discriminated unions (if (result.ok)) let TypeScript know which branch you are in.
unknown, any and assertions
any switches checking off and spreads silently; avoid it. Use unknown for data you have not validated (API responses, JSON.parse) and narrow it. Type assertions (as User) are promises you make to the compiler; they are not checks.
Setup
Turn on "strict": true from day one. Use tsc --noEmit in CI because many bundlers strip types without checking them.
Good enough to move on
You can type a small app's data model, functions and API responses under strict mode without reaching for any, and use a discriminated union for loading/success/error state.
Key concepts
- Type annotations and inference
- type aliases and interfaces
- Union and literal types
- Optional, null and undefined
- Narrowing and type guards
- Discriminated unions
- any vs unknown vs never
- Typing functions and callbacks
- Strict mode
Mini project
Port a vanilla JavaScript project (for example your fetch-based weather or movie app) to TypeScript with strict mode, typing API responses as unknown and narrowing them before use.
Check yourself
Why is `const data = await res.json() as User` less safe than parsing into unknown and narrowing?
Free resources
- The TypeScript Handbook (TypeScript)
- TypeScript for JavaScript Programmers (TypeScript)
- TypeScript Playground (TypeScript)