typescript-patterns
Installation
SKILL.md
TypeScript Patterns
Apply these patterns when writing, reviewing, or refactoring TypeScript code. Prefer type safety over convenience. Catch errors at compile time, not runtime.
Type Design Principles
Default to the narrowest type that accurately represents the data. Widen only when you have a concrete reason.
| Principle | Do | Don't |
|---|---|---|
| Narrow types | status: "active" | "inactive" |
status: string |
| Branded types for IDs | type UserId = string & { __brand: "UserId" } |
userId: string (mixable with any string) |
| Discriminated unions | { kind: "circle"; radius: number } | { kind: "rect"; w: number; h: number } |
Type assertions to distinguish shapes |
| Readonly by default | readonly items: Item[] |
Mutable arrays unless mutation is required |
| Explicit return types on public APIs | function getUser(id: UserId): Promise<User> |
Inferred return types on exported functions |
Branded Types
Use branded types to prevent accidental mixing of structurally identical values: