AI4Dev Team
AI Development Expert
Type Safety with AI APIs
Always use proper TypeScript types when working with AI APIs. Here's a pattern that saves hours of debugging in production.
// Define your response shape before writing API calls
interface AICompletionResult<T> {
data: T;
usage: {
promptTokens: number;
completionTokens: number;
totalTokens: number;
};
model: string;
finishReason: 'stop' | 'length' | 'tool_use';
}
// Strongly-typed wrapper around Anthropic SDK
async function askClaude<T>(
prompt: string,
parseResponse: (text: string) => T
): Promise<AICompletionResult<T>> {
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-6',
max_tokens: 1024,
messages: [{ role: 'user', content: prompt }],
});
const text = response.content[0].type === 'text'
? response.content[0].text
: '';
return {
data: parseResponse(text),
usage: {
promptTokens: response.usage.input_tokens,
completionTokens: response.usage.output_tokens,
totalTokens: response.usage.input_tokens + response.usage.output_tokens,
},
model: response.model,
finishReason: response.stop_reason as AICompletionResult<T>['finishReason'],
};
}
The key insight: define your types before writing API calls, not after. This forces you to think about the shape of data you need upfront, and TypeScript will catch mismatches at compile time.
This pattern also makes it easy to mock in tests — you only need to stub the parseResponse function.
What TypeScript patterns do you use with AI APIs? Share in the comments!