--- name: typescript-patterns description: TypeScript best practices and patterns. Use when writing TypeScript, fixing type errors, or working with generics. version: 1.0.0 format: 2025-10-02 triggers: - "writing TypeScript, fixing type errors, or working with generics" updated: 2026-04-25 status: ACTIVE --- # TypeScript Patterns ## Type vs Interface | Use Case | Prefer | |----------|--------| | Object shape | interface | | Union types | type | | Extending shapes | interface | | Intersection | type | | Tuple/primitives | type | ## Key Patterns **Discriminated Unions** — model state with tagged types: ```typescript type Result = { ok: true; value: T } | { ok: false; error: Error }; ``` **Type Guards** — narrow at runtime: ```typescript function isUser(obj: unknown): obj is User { return typeof obj === 'object' && obj !== null && 'id' in obj; } ``` **Generic Constraints:** ```typescript function getProperty(obj: T, key: K): T[K] { return obj[key]; } ``` ## Utility Types | Type | Purpose | |------|---------| | Partial\ | All optional | | Required\ | All required | | Pick\ | Select properties | | Omit\ | Remove properties | | Record\ | Key-value map | | ReturnType\ | Function return type | ## Avoid - `any` — use `unknown` and narrow - Type assertions (`as`) — use type guards - `!` operator — handle null properly - Missing return types on complex functions