Interfaces and Type Aliases
Choose between interface and type for object shapes, extend and compose types, and know when declaration merging matters.
TypeScript names object shapes with interface and type alias. Both describe fields, optional properties, and methods. Most daily code works identically with either. Differences appear at scale: interfaces merge across declarations; type aliases express unions, tuples, and mapped types interfaces cannot.
Consistency within a module matters more than dogma. Public library contracts often use interface for extendability. Application code uses type for unions, Zod-inferred shapes, and utility compositions.
Interface basics and extension
extends layers interfaces like inheritance for shape only. Optional ? properties may be absent. readonly prevents reassignment after initialization — useful for DTOs from read-only API responses.
Type aliases — unions and intersections
Only type aliases can form unions directly. Intersections combine types with & — AuditedProduct = Product & Timestamps. Function type aliases document comparator and mapper signatures cleanly.
Declaration merging and Record
Duplicate interface names merge members — useful augmenting third-party types in .d.ts files. Type aliases never merge. Prefer Record<K, V> over raw index signatures for simple dictionaries — clearer intent and better errors.
| Feature | interface | type |
|---|---|---|
| Unions | No | Yes |
| Merging | Yes | No |
| Mapped types | No | Yes |
implements and class contracts
Classes implement interfaces or type aliases to guarantee public shape. TypeScript checks structural compatibility — missing methods error at class declaration, not at first use.
Interface merging lets you augment global types in declaration files — for example adding custom properties to a Window interface in browser code. Type aliases cannot merge, which prevents accidental duplicate-name collisions in application code.
- extends for layered interfaces
- type for unions and intersections
- Record for string-key maps
- 1interface extends shapes
- 2type for unions
- 3Record over index signatures
- 4Next: generics fundamentals