CodeOath
← All posts
TypeScript75 min total · 21 parts

TypeScript Fundamentals: Types, Interfaces, Generics, and Why It Catches Bugs Before Runtime

Contents — Part 21 of 21: Common Mistakes Worth Remembering
Part 21 of 21 · ~1 min

Common Mistakes Worth Remembering

  • Reaching for any to make a compiler error go away instead of fixing the actual type mismatch — this silences the exact safety net TypeScript exists to provide, and the any typically spreads to everything downstream of it.
  • Assuming interface/type guarantee runtime validation — they don't; TypeScript's types are erased entirely at compile time, so data from an API still needs real runtime validation (a schema library, or at minimum manual checks) if it might not match what you typed.
  • Not narrowing a union type before using type-specific methods, then working around the resulting compiler error with a type assertion (as) instead of an actual check.
  • Using as/! to silence a compiler error at the exact spot the compiler was trying to warn you about a real, possible bug — both are compile-time-only promises with no runtime check behind them.
  • Forgetting that object literals get extra "excess property" checking that structurally-equivalent variables don't — leading to confusion about why one assignment errors and a seemingly identical one doesn't.
  • Shipping without strictNullChecks (or strict generally) and assuming TypeScript is protecting against null/undefined bugs it was never configured to catch.
  • Widening a literal by forgetting as const, then being surprised a value typed as the general string doesn't satisfy a narrower literal union parameter.

TypeScript is the language most real React applications are written in today — see React Fundamentals for the component and hooks side of that pairing, and JavaScript Core Concepts for the runtime behavior TypeScript's types sit on top of. Practice these exact patterns — narrowing, generics, and the type-erasure gotchas — as runnable exercises in the code lab.