TypeScript Fundamentals

TypeScript Mental Model

TypeScript is a static typechecker for JavaScript. It analyzes your code before runtime, reports likely type mistakes, and then emits JavaScript; its types do not exist unless you also write runtime checks.
  • TypeScript checks programs; JavaScript runs programs
  • Types are erased
  • Assertions are not validation
  • Unknown data should enter as unknown
  • TypeScript works best with strict project settings
Compile-time vs runtime
The runtime never sees your TypeScript interface.
Assertion vs validation
type User = { id: string; name: string }

const raw = await response.json()

const user1 = raw as User
// Compiler is quiet, but runtime value may be anything.

const user2 = parseUser(raw)
// Runtime validation proves the shape before returning User.
The type assertion is a claim; the parser is a check.
What TypeScript can and cannot do
Can help withCannot prove by itself
Internal function callsExternal API response shape
Property names and return typesDatabase contents are valid
Exhaustive union handlingUser input follows schema
Refactoring confidenceRuntime environment has required APIs
Library API contractsDeclaration files match implementation
Sources
  • The TypeScript HandbookAbout this Handbook
  • Effective TypeScript, 2nd EditionTypeScript's type system
  • MDN JavaScript Guide and ReferenceJavaScript runtime basics