## Why TypeScript for AI?
TypeScript catches bugs at compile time, provides autocompletion, and documents your AI interfaces — critical when working with untyped API responses.
### Typed API Wrappers
```typescript interface ChatMessage { role: "system" | "user" | "assistant"; content: string; }
interface ChatOptions { model: "gpt-4o" | "gpt-4o-mini" | "claude-sonnet-4-20250514"; messages: ChatMessage[]; temperature?: number; maxTokens?: number; stream?: boolean; }
interface ChatResponse { content: string; model: string; usage: { promptTokens: number; completionTokens: number; totalTokens: number }; finishReason: "stop" | "length" | "tool_calls"; }
async function chat(options: ChatOptions): Promise<ChatResponse> { // Route to appropriate provider based on model if (options.model.startsWith("gpt")) return callOpenAI(options); if (options.model.startsWith("claude")) return callAnthropic(options); throw new Error(`Unknown model: ${options.model}`); } ```
### Discriminated Union for Tool Calls
```typescript type ToolCall = | { type: "web_search"; query: string } | { type: "database_query"; sql: string; database: string } | { type: "send_email"; to: string; subject: string; body: string };
function executeToolCall(call: ToolCall): Promise<string> { switch (call.type) { case "web_search": return searchWeb(call.query); case "database_query": return queryDB(call.sql, call.database); case "send_email": return sendEmail(call.to, call.subject, call.body); } } ```
### Benefits
- Catch model name typos at compile time
- Autocomplete tool call properties
- Exhaustive switch checks for tool types
- Self-documenting API interfaces