1---2name: typescript-133description: Provides comprehensive TypeScript development expertise and coding standards. Ensures type safety through strict type checking, implements clean code patterns, and maintains consistent architectural decisions. Specializes in advanced type system features including generics, conditional types, mapped types, and template literal types. Use when: working with TypeScript files (.ts/.tsx), defining type definitions and interfaces, implementing generic programming patterns, designing type-safe APIs, handling complex type transformations, integrating TypeScript with React/Vue/Angular frameworks, configuring strict mode settings, resolving type errors, or optimizing type performance in large codebases.4---5
6# TypeScript Coding Standards
7
8## Basic Principles
9
10### One Function, One Responsibility
11
12- If function name connects with "and" or "or", it's a signal to split
13- If test cases are needed for each if branch, it's a signal to split
14
15### Conditional and Loop Depth Limited to 2 Levels
16
17- Minimize depth using early return whenever possible
18- If still heavy, extract into separate functions
19
20### Make Function Side Effects Explicit
21
22- Example: If `getUser` also runs `updateLastAccess()`, specify it in the function name
23
24### Convert Magic Numbers/Strings to Constants When Possible
25
26- Declare at the top of the file or class where used
27- Consider separating into a constants file if there are many
28
29### Function Order by Call Order
30
31- Follow class access modifier declaration order rules if clear
32- Otherwise, order top-to-bottom for easy reading by call order
33
34### Review External Libraries for Complex Implementations
35
36- When logic is complex and tests become bloated
37- If industry-standard libraries exist, use them
38- When security, accuracy, or performance optimization is critical
39- When browser/platform compatibility or edge cases are numerous
40
41### Modularization (Prevent Code Duplication and Pattern Repetition)
42
43- Absolutely forbid code repetition
44- Modularize similar patterns into reusable forms
45- Allow pre-modularization if reuse is confirmed
46- Avoid excessive abstraction
47- Modularization levels:
48 - Same file: Extract into separate function
49 - Multiple files: Separate into different file
50 - Multiple projects/domains: Separate into package
51
52### Variable and Function Names
53
54- Clear purpose while being concise
55- Forbid abbreviations outside industry standards (id, api, db, err, etc.)
56- Don't repeat context from the parent scope
57- Boolean variables use `is`, `has`, `should` prefixes
58- Function names are verbs or verb+noun forms
59- Plural rules:
60 - Pure arrays: "s" suffix (`users`)
61 - Wrapped object: "list" suffix (`userList`)
62 - Specific data structure: Explicit (`userSet`, `userMap`)
63 - Already plural words: Use as-is
64
65### Field Order
66
67- Alphabetically ascending by default
68- Maintain consistency in usage
69- Also alphabetically ordered in destructuring assignment
70
71### Error Handling
72
73- Error handling level: Handle where meaningful response is possible
74- Error messages: Technical details for logs, actionable guidance for users
75- Error classification: Distinguish between expected and unexpected errors
76- Error propagation: Add context when propagating up the call stack
77- Recovery vs. fast fail: Recover from expected errors with fallback
78- Error types: For domain-specific failures, create custom error classes extending `Error`. Never throw non-Error objects
79- Async errors: Always handle Promise rejection. Use try-catch for async/await, .catch() for promise chains
80
81## Package Management
82
83### Package Manager
84
85- Use pnpm as default package manager
86- Forbid npm, yarn (prevent lock file conflicts)
87
88## File Structure
89
90### Common for All Files
91
921. Import statements (grouped)
932. Constant definitions (alphabetically ordered if multiple)
943. Type/Interface definitions (alphabetically ordered if multiple)
954. Main content (see below)
96
97### Inside Classes
98
99- Decorators
100- private readonly members
101- readonly members
102- constructor
103- public methods (alphabetically ordered)
104- protected methods (alphabetically ordered)
105- private methods (alphabetically ordered)
106
107### Function Placement in Function-Based Files
108
109- Main exported function
110- Additional exported functions (alphabetically ordered, avoid many)
111- Helper functions
112
113## Function Writing
114
115### Use Arrow Functions
116
117- Always use arrow functions except for class methods
118- Forbid function keyword entirely (exceptions: generator function\*, function hoisting etc. technically impossible cases only)
119
120### Function Arguments: Flat vs Object
121
122- Use flat if single argument or uncertain of future additions
123- Use object form for 2+ arguments in most cases. Allow flat form when:
124 - All required arguments without boolean arguments
125 - All required arguments with clear order (e.g., (width,height), (start,end), (min,max), (from,to))
126
127## Type System
128
129### Type Safety
130
131- Forbid unsafe type bypasses like any, as, !, @ts-ignore, @ts-expect-error
132- Exceptions: Missing or incorrect external library types, rapid development needed (clarify reason in comments)
133- Allow some unknown type when type guard is clear
134- Allow as assertion when literal type (as const) needed
135- Allow as assertion when widening literal/HTML types to broader types
136- Allow "!" assertion when type narrowing impossible after type guard due to TypeScript limitation
137- Allow @ts-ignore, @ts-expect-error in test code (absolutely forbid in production)
138
139### Interface vs Type
140
141- Prioritize Type in all cases by default
142- Use Interface only for these exceptions:
143 - Public API provided to external users like library public API
144 - Need to extend existing interface like external libraries
145 - Designing OOP-style classes where implementation contract must be clearly defined
146
147### null/undefined Handling
148
149- Actively use Optional Chaining (`?.`)
150- Provide defaults with Nullish Coalescing (`??`)
151- Distinguish between `null` and `undefined` by semantic meaning:
152 - `undefined`: Uninitialized state, optional parameters, value not assigned yet
153 - `null`: Intentional absence of value (similar to Go's nil)
154- Examples:
155 - Optional field: `{ name?: string }` → can be `undefined`
156 - Intentionally cleared value: `user.profileImage = null`
157 - External API responses may use either convention
158
159## Code Style
160
161### Maintain Immutability
162
163- Use `const` whenever possible, minimize `let`
164- Create new values instead of directly modifying arrays/objects
165- Use `spread`, `filter`, `map` instead of `push`, `splice`
166- Exceptions: Extremely performance-critical cases
167
168## Recommended Libraries
169
170- Testing: Jest, Playwright
171- Utilities: es-toolkit, dayjs
172- HTTP: ky, @tanstack/query, @apollo/client
173- Form: React Hook Form
174- Type validation: zod
175- UI: Tailwind + shadcn/ui
176- ORM: Prisma (Drizzle if edge support important)
177- State management: zustand
178- Code formatting: prettier, eslint
179- Build: tsup