TypeScript Patterns
Iron Law
UNKNOWN OVER ANY
Never use
any. Useunknownwith type guards instead.anydisables TypeScript's
entire value proposition — if you need flexibility, use generics; if you need to handle
arbitrary data, use
unknownand validate.anyis giving up. [1, Item 43]
Type Safety
- Return
unknownfrom untyped sources (JSON.parse), then narrow with a type guard (if (isUser(data))), not a cast (data as User). - Handle null and undefined explicitly:
user?.name ?? fallback, notuser!.name!. - End a switch over a union with an exhaustive check,
default: const _: never = status;, notdefault: 'unknown'. - Use type-only imports (
import type). - Use a strict tsconfig:
strict,noUncheckedIndexedAccess.
Generic Patterns
- Use generics for flexibility:
first<T>(items: T[]): T | undefined. - Constrain key access:
getProperty<T, K extends keyof T>(obj: T, key: K): T[K]. - Give a generic interface a default parameter:
Repository<T, ID = string>.
Discriminated Unions
Make illegal states unrepresentable: encode each variant in the type, for results and request states.
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
Branded Types
Structural typing treats UserId and OrderId (both string) as identical.
Brand IDs and amounts for nominal distinction with zero runtime cost.
declare const brand: unique symbol;
type Brand<T, B> = T & { [brand]: B };
type UserId = Brand<string, 'UserId'>; // getUser(orderId) is a compile error
Conditional & Mapped Types
- Unwrap with
infer:T extends (...args: any[]) => Promise<infer R> ? R : never. - Remap keys with
as:{ [K in keyof T as T[K] extends V ? K : never]: T[K] }. - Recurse for deep forms:
DeepReadonly<T> = { readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P] }.
Extended References
references/sources.md— Full bibliographyreferences/patterns.md— Extended patterns with citationsreferences/violations.md— Violation examples with citationsreferences/utility-types.md— Utility types, branded types, template literalsreferences/type-guards.md— Advanced type guard patternsreferences/async.md— Async TypeScript patterns