← Blog

Claude API TypeScript SDK Best Practices

2026-11-19 · 4 min read · SubToAPI Team

If you're building a TypeScript app on Claude, the question isn't just "how do I call the API" — it's how to structure your types, handle streaming, manage retries, and avoid the runtime surprises that untyped API responses tend to produce. This article covers the practical patterns that keep a Claude integration maintainable as it grows past a weekend prototype.

The short answer: type your request and response shapes explicitly rather than relying on any, centralize your API client in one module, handle rate limits and transient errors with exponential backoff, and treat streaming as a first-class citizen in your type definitions rather than an afterthought. The rest of this guide walks through each of these in detail.

Set Up a Typed Client Module

Don't scatter fetch calls across your codebase. Wrap your Claude client in a single module that owns configuration, headers, and error normalization:

interface ClaudeMessage {
  role: "user" | "assistant";
  content: string;
}

interface ClaudeRequest {
  model: string;
  max_tokens: number;
  messages: ClaudeMessage[];
}

interface ClaudeResponse {
  id: string;
  content: { type: string; text: string }[];
  usage: { input_tokens: number; output_tokens: number };
}

async function callClaude(req: ClaudeRequest): Promise<ClaudeResponse> {
  const res = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "x-api-key": process.env.ANTHROPIC_API_KEY ?? "",
      "anthropic-version": "2023-06-01",
      "content-type": "application/json",
    },
    body: JSON.stringify(req),
  });

  if (!res.ok) {
    throw new Error(`Claude API error: ${res.status}`);
  }

  return res.json() as Promise<ClaudeResponse>;
}

This gives you one place to add retries, logging, and type guards instead of duplicating fetch logic everywhere you need a completion.

Use Discriminated Unions for Content Blocks

Claude responses can contain multiple content block types — text, tool calls, thinking blocks. Model this with a discriminated union instead of a loose object:

type ContentBlock =
  | { type: "text"; text: string }
  | { type: "tool_use"; id: string; name: string; input: Record<string, unknown> };

function extractText(blocks: ContentBlock[]): string {
  return blocks
    .filter((b): b is { type: "text"; text: string } => b.type === "text")
    .map((b) => b.text)
    .join("\n");
}

This pattern pays off the moment you add tool calling — TypeScript will force you to handle each block type explicitly instead of hoping block.text exists.

Handle Streaming Properly

Streaming responses arrive as server-sent events, and the naive approach of treating the whole body as a string loses the incremental benefit entirely. Use a ReadableStream reader and parse line by line:

async function streamClaude(req: ClaudeRequest, onChunk: (text: string) => void) {
  const res = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "x-api-key": process.env.ANTHROPIC_API_KEY ?? "",
      "anthropic-version": "2023-06-01",
      "content-type": "application/json",
    },
    body: JSON.stringify({ ...req, stream: true }),
  });

  const reader = res.body?.getReader();
  const decoder = new TextDecoder();
  if (!reader) return;

  let buffer = "";
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });
    const lines = buffer.split("\n");
    buffer = lines.pop() ?? "";
    for (const line of lines) {
      if (line.startsWith("data: ")) {
        const payload = line.slice(6);
        if (payload === "[DONE]") return;
        const event = JSON.parse(payload);
        if (event.delta?.text) onChunk(event.delta.text);
      }
    }
  }
}

Define a type for the delta events too — don't let JSON.parse return any and propagate untyped data into your UI layer.

Retry with Backoff, Not Blind Loops

Rate limits (429) and transient 5xx errors are normal at scale. Wrap calls in a retry helper with exponential backoff and jitter, and respect Retry-After headers when present:

async function withRetry<T>(fn: () => Promise<T>, attempts = 3): Promise<T> {
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (err) {
      if (i === attempts - 1) throw err;
      const delay = 2 ** i * 500 + Math.random() * 200;
      await new Promise((r) => setTimeout(r, delay));
    }
  }
  throw new Error("unreachable");
}

Keep this logic in your client module, not sprinkled through business logic.

Validate Inputs Before You Send Them

TypeScript types disappear at runtime, so if your max_tokens or model values come from user input or config files, validate them with a schema library like Zod before constructing the request. This catches malformed requests before they hit the network and produce a confusing 400.

Keep Secrets Out of Client Bundles

A common mistake in TypeScript projects that span frontend and backend is importing the API client into frontend code, which bundles the API key into the browser. Keep all Claude calls server-side, and expose only the endpoints your frontend actually needs through your own API routes.

Simplify with a Managed Gateway

Writing and maintaining all of the above — typed wrappers, streaming parsers, retry logic, rate-limit handling — is doable but repetitive across projects. SubToAPI turns your existing Claude access into a standard HTTPS API with application keys (sub_live_...), built-in streaming, tool use, and usage metadata, so your TypeScript client code talks to one stable endpoint instead of reimplementing retry and parsing logic per project. The quickstart shows the full request shape, and the streaming docs cover the SSE format in detail. Plans start at Solo €9, with Team and Scale tiers for multi-seat setups — see pricing — and a free trial is available at signup.

FAQ

Does Claude have an official TypeScript SDK? Anthropic provides an official SDK, but many teams build a thin typed wrapper around fetch or a gateway API to keep full control over retries, streaming parsing, and response typing specific to their app.

How should I type tool_use responses in TypeScript? Use a discriminated union on the type field for content blocks (text vs tool_use), and define a separate interface for the input shape of each tool so TypeScript can validate arguments at compile time.

What's the biggest mistake developers make with the Claude API in TypeScript? Treating API responses as any and skipping runtime validation. This hides malformed streaming events and bad tool inputs until they crash in production rather than at the type-checking stage.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →