TypeScript Fundamentals

Structural Typing

TypeScript is mostly structurally typed: compatibility is based on shape rather than declared name. If a value has the required properties, it can usually be used as that type.
  • Shape matters more than names
  • This matches JavaScript's object model
  • Structural typing makes APIs flexible
  • It can blur domain boundaries
  • Classes are not automatically nominal
Different names, same shape
type User = { id: string }
type Product = { id: string }

const product: Product = { id: "p1" }
const user: User = product // allowed: same structure
This is convenient until two domain concepts share the same shape but should not mix.
Typing models
ModelCompatibility based onExample
NominalDeclared identity/nameJava class hierarchy
StructuralRequired shapeTypeScript object types
Branded structuralShape + phantom markerUserId vs ProductId
Runtime validationActual value checkParser/schema
Sources
  • The TypeScript HandbookType Compatibility
  • Effective TypeScript, 2nd EditionStructural typing
  • TypeScript ReferenceAssignability