Type-Safe AI SDK Wrappers
From the course TypeScript for AI Applications
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
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
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
Common Pitfall: Using any for API Response Types
TypeScript's any type defeats the purpose of type-safe AI wrappers. When you type a function as returning Promise<any>, callers get no autocomplete or compile-time checks on the response. Create explicit interfaces for every AI response shape:
// Bad: caller gets no type information
async function analyze(text: string): Promise<any> { ... }
// Good: caller knows exactly what they receive
interface AnalysisResult {
sentiment: "positive" | "negative" | "neutral";
confidence: number;
topics: string[];
summary: string;
}
async function analyze(text: string): Promise<AnalysisResult> { ... }
Best Practice: Use Const Assertions for Model Lists
Maintain a list of valid model names as a const enum to catch typos at compile time and keep a single source of truth:
const OPENAI_MODELS = ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo"] as const;
type OpenAIModel = typeof OPENAI_MODELS[number]; // Union type
function callOpenAI(model: OpenAIModel, prompt: string) {
// TypeScript will error if you pass an invalid model name
}
callOpenAI("gpt-4o", "Hello"); // OK
callOpenAI("gpt-5", "Hello"); // TypeScript error: not in the union
Named Product Reference: Zod + OpenAI Structured Outputs
OpenAI's Structured Outputs feature (available on gpt-4o and later) guarantees that the model's response exactly matches a provided JSON Schema. Combined with zodToJsonSchema from the zod-to-json-schema package, you define the schema once in Zod and it works as both the API constraint (preventing invalid JSON) and the TypeScript type (through z.infer). This eliminates the need to handle parse errors from malformed AI output entirely.
Key Takeaways
- •TypeScript catches AI API bugs at compile time
- •Use discriminated unions for type-safe tool call handling
- •Typed wrappers provide autocomplete and documentation
- •Route between providers with a unified typed interface
Progress is kept in this browser only.