AT

AI4Dev Team

AI Development Expert

Mar 10, 2026·Public
Tip

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!

#TypeScript#AI#Tips

More from the feed

AT

AI4Dev Team

AI4Dev Blog

Mar 08, 2026·
Achievement

500 Newsletter Subscribers!

We just hit 500 newsletter subscribers! Thank you to every developer who joined our AI integration community. Here's what's coming next.

See more
#Milestone#Community#News
AT

AI4Dev Team

AI Development Expert

Mar 07, 2026·
Question

Channels vs Message Queue for AI Processing?

When building a background AI processing pipeline in .NET, when do you choose System.Threading.Channels over a message queue like RabbitMQ or Azure Service Bus? Curious about your experience.

See more
#dotnet#AI#Architecture#Question