copilot-instructions.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# TypeScript Strict Mode Instructions ## TypeScript Configuration Use strict TypeScript configuration: ```json{ "compilerOptions": { "strict": true, "noUncheckedIndexedAccess": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "noUnusedLocals": true, "noUnusedParameters": true, "exactOptionalPropertyTypes": true, "forceConsistentCasingInFileNames": true }}``` ## Type Safety Rules ### 1. Explicit Return Types```typescript// ✅ Good: Explicit return typefunction calculateTotal(items: Item[]): number { return items.reduce((sum, item) => sum + item.price, 0);} // ❌ Bad: Implicit return typefunction calculateTotal(items: Item[]) { return items.reduce((sum, item) => sum + item.price, 0);}``` ### 2. No Any Types```typescript// ✅ Good: Proper typinginterface User { id: string; name: string; email: string;} function processUser(user: User): void { console.log(user.name);} // ❌ Bad: Using anyfunction processUser(user: any): void { console.log(user.name);}``` ### 3. Strict Null Checks```typescript// ✅ Good: Handle null/undefinedfunction getUserName(user: User | null): string { return user?.name ?? "Anonymous";} // ❌ Bad: Assuming non-nullfunction getUserName(user: User): string { return user.name; // Could be null}``` ### 4. Type Guards```typescript// ✅ Good: Type guardfunction isUser(value: unknown): value is User { return ( typeof value === "object" && value !== null && "id" in value && "name" in value );} // ❌ Bad: Type assertion without checkconst user = data as User;``` ## Code Organization ### 1. File Structure```src/ types/ user.ts → User-related types api.ts → API response types database.ts → Database model types lib/ utils.ts → Utility functions validation.ts → Zod schemas components/ ui/ → Reusable UI components``` ### 2. Type Definitions```typescript// Define types in separate files// types/user.tsexport interface User { id: string; name: string; email: string; createdAt: Date;} export type UserRole = "admin" | "user" | "guest"; export interface AuthUser extends User { role: UserRole; permissions: string[];}``` ### 3. Zod for Runtime Validation```typescriptimport { z } from "zod"; // Define schemaexport const userSchema = z.object({ id: z.string().uuid(), name: z.string().min(1).max(100), email: z.string().email(), createdAt: z.date(),}); // Infer TypeScript type from schemaexport type User = z.infer<typeof userSchema>; // Validate at runtimeconst result = userSchema.safeParse(data);if (!result.success) { throw new Error(result.error.message);}``` ## Error Handling ### 1. Custom Error Classes```typescriptexport class AppError extends Error { constructor( message: string, public code: string, public statusCode: number = 500 ) { super(message); this.name = "AppError"; }} export class ValidationError extends AppError { constructor(message: string) { super(message, "VALIDATION_ERROR", 400); }}``` ### 2. Result Type Pattern```typescripttype Result<T, E = Error> = | { success: true; data: T } | { success: false; error: E }; async function fetchUser(id: string): Promise<Result<User>> { try { const user = await db.user.findUnique({ where: { id } }); if (!user) { return { success: false, error: new Error("User not found") }; } return { success: true, data: user }; } catch (error) { return { success: false, error: error as Error }; }}``` ## Best Practices 1. **Always define explicit types** for function parameters and returns2. **Use interfaces for objects**, types for unions/intersections3. **Prefer readonly** for immutable data4. **Use const assertions** for literal types5. **Implement discriminated unions** for complex state6. **Use generics** for reusable type-safe functions7. **Avoid type assertions** unless absolutely necessary8. **Use utility types** (Partial, Pick, Omit, etc.)9. **Define branded types** for nominal typing10. **Use template literal types** for string patterns ## Code Quality Tools ### ESLint Configuration```json{ "extends": ["next/core-web-vitals","plugin:@typescript-eslint/recommended","plugin:@typescript-eslint/recommended-requiring-type-checking" ], "rules": { "@typescript-eslint/no-explicit-any": "error", "@typescript-eslint/no-unused-vars": "error", "@typescript-eslint/explicit-function-return-type": "warn" }}``` ### Prettier Configuration```json{ "semi": true, "trailingComma": "es5", "singleQuote": false, "printWidth": 80, "tabWidth": 2, "useTabs": false}```
Copilot InstructionsMarkdown