03-frontend

TypeScript

03-frontend/typescript

TypeScript

Overview

TypeScript adds static structure to JavaScript so large frontend codebases stay safer to change.


Why It Matters

Types catch mistakes early, document intent, and make refactoring less risky.


Core Concepts

  • Types model valid states.
  • Inference is usually better than manual annotation.
  • Narrow types where behavior depends on them.

Mental Models

Use types to describe the business contract, not to fight the compiler.


Best Practices

  • Let inference work first.
  • Create types at boundaries.
  • Prefer discriminated unions for multiple states.

Common Mistakes

  • Over-annotating everything.
  • Using any to escape design problems.
  • Repeating runtime checks that the type system could express.

Trade-offs

Stricter types improve confidence, but too much type machinery can hide simple logic.


Decision Framework

SituationPrefer
Simple valueInference
External inputValidation plus types
Multi-state UIDiscriminated union

Examples

type LoadState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "error"; message: string }
  | { status: "success"; data: string[] };

Checklists

  • Are external inputs validated?
  • Does the type model real states only?
  • Did I avoid any unless absolutely necessary?

Senior Engineer Notes

Senior engineers use TypeScript to reduce ambiguity, not to impress the compiler. Types should make the code easier to change safely.


Further Reading