Bỏ qua để vào nội dung chính
TypeScript Type Generation Prompts: Let AI Write Your Complex Types

TypeScript Type Generation Prompts: Let AI Write Your Complex Types

Bởi Ethan Carter
17 thg 3, 20266 phút đọc

Complex TypeScript generics and utility types are where AI coding assistants truly shine. Learn the prompts that produce correct, well-documented type definitions for your hardest typing challenges.

Why AI Excels at TypeScript Types

TypeScript's type system is a domain-specific language. Writing complex generics, conditional types, and mapped types requires deep expertise that most developers only partially possess. AI models have seen millions of TypeScript files and can navigate the type system's most obscure corners — if you know how to prompt them.

Prompting for Generic Utility Types

Write a TypeScript utility type that:

[DESCRIBE THE TRANSFORMATION]

Requirements:
- [CONSTRAINT 1]
- [CONSTRAINT 2]

Examples:
Input type: [EXAMPLE INPUT]
Expected output type: [EXPECTED OUTPUT]

Edge cases to handle:
- [EDGE CASE 1]
- [EDGE CASE 2]

Add JSDoc explaining how it works and when to use it.

Example: API Response Wrapper Type

Write a TypeScript generic type for wrapping API responses.

Requirements:
- Success case: { data: T, error: null, status: 'success' }
- Error case: { data: null, error: ErrorType, status: 'error' }
- Loading case: { data: null, error: null, status: 'loading' }

The type should:
- Be a discriminated union based on status
- Allow TypeScript to narrow correctly in if/switch statements
- Work as: ApiResponse<User>, ApiResponse<Post[]>
- Have a helper function isSuccess(result) that narrows the type

Edge cases:
- T might itself be undefined or null
- The error should default to a standard error type if not specified

This produces:

type ApiResponse<T, E = ApiError> =
  | { data: T; error: null; status: 'success' }
  | { data: null; error: E; status: 'error' }
  | { data: null; error: null; status: 'loading' };

function isSuccess<T, E>(result: ApiResponse<T, E>): result is { data: T; error: null; status: 'success' } {
  return result.status === 'success';
}

Prompting for Prisma Type Utilities

I use Prisma ORM. Write utility types that:

1. ExtractPrismaModel<T> - extracts the return type of a Prisma findUnique call
   Usage: type UserModel = ExtractPrismaModel<typeof db.user.findUnique>

2. WithRelations<T, K extends string> - adds optional relation fields to a base type
   Usage: type PostWithAuthor = WithRelations<Post, 'author' | 'comments'>

3. PrismaInput<T> - creates the "create input" type from a model type
   Should exclude auto-generated fields: id, createdAt, updatedAt

All types must have JSDoc examples showing usage.

Prompting for Form Schema Types

I use Zod for form validation. Create a pattern for:

1. A base schema for each entity (for validation)
2. An inferred TypeScript type from the schema
3. A "partial" schema for update operations (all fields optional)
4. Helper types for React Hook Form integration

Example entity: BlogPost with fields:
- title: string, min 5 chars, max 100
- content: string, min 50 chars
- categoryId: string, valid UUID format
- tags: array of strings, max 10
- status: "DRAFT" | "PUBLISHED" | "ARCHIVED"
- publishedAt: optional Date

Show the complete pattern I should replicate for all entities.

Debugging Type Errors With AI

When you hit a cryptic TypeScript error, the most effective prompt is:

I have this TypeScript error:
[PASTE THE FULL ERROR MESSAGE]

In this code:
[PASTE THE RELEVANT CODE]

Explain:
1. Why exactly this error occurs (trace through the type checking)
2. What the correct fix is
3. Are there any alternative approaches?
4. Is there a pattern I should adopt to prevent this class of error?

Type-First Development

The most effective workflow: write types first with AI, then implement against the types. "Write the complete TypeScript interface for a checkout flow, including all possible states and transitions" produces a type specification you can implement against — and AI implements much better when the types are already defined.

Không spam, hủy đăng ký bất kỳ lúc nào.

Bài viết liên quan