--- name: typescript-skill description: TypeScript coding patterns and type safety guide. Use when writing, reviewing, or debugging TypeScript code. --- # TypeScript Skill ## Key Rules ### Always Prefer Explicit Types ```typescript // Bad const process = (data: any) => data.value; // Good interface GameState { value: number; } const process = (data: GameState): number => data.value; ``` ### Use `unknown` Instead of `any` ```typescript // Bad function parse(input: any) { return input.name; } // Good function parse(input: unknown): string { if (typeof input === 'object' && input !== null && 'name' in input) { return String((input as { name: unknown }).name); } throw new Error('Invalid input'); } ``` ### Prefer `const` Assertions for Literals ```typescript const DIRECTIONS = ['up', 'down', 'left', 'right'] as const; type Direction = typeof DIRECTIONS[number]; // 'up' | 'down' | 'left' | 'right' ``` ## Common Patterns | Pattern | Use Case | |---------|----------| | `type` | Unions, intersections, primitives | | `interface` | Object shapes (extendable) | | `enum` | Named constants (prefer `as const` for simple cases) | | `generic ` | Reusable, type-safe utilities |