Anthropic TypeScript SDK Guide (2026)

Complete reference for @anthropic-ai/sdk in TypeScript. Types, configuration, messages API, streaming, tool use, prompt caching, and error handling with full code examples.

🔥 Launch tonight — Power Prompts PDF 50p (just 50p tonight)30 battle-tested Claude Code prompts · 8 pages · paste into CLAUDE.md · price reverts to £5

The @anthropic-ai/sdk TypeScript package ships full type definitions for every API surface. This reference covers all major patterns with TypeScript-first examples.

Install & configure

npm install @anthropic-ai/sdk
# TypeScript 4.7+ required for correct generic inference
import Anthropic from "@anthropic-ai/sdk";

// Option 1: reads ANTHROPIC_API_KEY from process.env
const client = new Anthropic();

// Option 2: explicit key (never commit — use env vars or secrets manager)
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

// Option 3: custom base URL (useful for local proxies)
const client = new Anthropic({ baseURL: "https://your-proxy.example.com" });

Key TypeScript types

import type {
  Message,           // full response object
  MessageParam,      // { role, content } message
  ContentBlock,      // TextBlock | ToolUseBlock
  TextBlock,         // { type: "text"; text: string }
  ToolUseBlock,      // { type: "tool_use"; id; name; input }
  ToolResultBlock,   // { type: "tool_result"; tool_use_id; content }
  Tool,              // tool definition schema
  MessageStreamEvent // union of all SSE event types
} from "@anthropic-ai/sdk/resources/messages";

Type-safe message creation

import type { MessageCreateParamsNonStreaming } from "@anthropic-ai/sdk/resources/messages";

const params: MessageCreateParamsNonStreaming = {
  model: "claude-sonnet-4-6",
  max_tokens: 1024,
  system: "You are a helpful assistant.",
  messages: [
    { role: "user", content: "What is a TypeScript discriminated union?" }
  ]
};

const response: Message = await client.messages.create(params);

Multi-modal content (vision)

const response = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 512,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "image",
          source: {
            type: "base64",
            media_type: "image/png",
            data: base64ImageData
          }
        },
        { type: "text", text: "Describe this diagram." }
      ]
    }
  ]
});

Typed tool use

import type { Tool } from "@anthropic-ai/sdk/resources/messages";

const weatherTool: Tool = {
  name: "get_weather",
  description: "Returns current conditions for a city.",
  input_schema: {
    type: "object" as const,
    properties: {
      city: { type: "string", description: "City name" },
      units: { type: "string", enum: ["celsius", "fahrenheit"] }
    },
    required: ["city"]
  }
};

const response = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 512,
  tools: [weatherTool],
  messages: [{ role: "user", content: "Weather in Berlin?" }]
});

Prompt caching with types

import type { TextBlockParam } from "@anthropic-ai/sdk/resources/messages";

const systemBlock: TextBlockParam = {
  type: "text",
  text: largeStaticContext,
  cache_control: { type: "ephemeral" }
};

const response = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 512,
  system: [systemBlock],
  messages: [{ role: "user", content: "Summarise this." }]
});

// Check cache performance
console.log("Cache read:", response.usage.cache_read_input_tokens);
console.log("Cache write:", response.usage.cache_creation_input_tokens);

Retry configuration

const client = new Anthropic({
  maxRetries: 3, // default is 2
  timeout: 60_000 // ms
});

Cost references

Frequently asked questions

What TypeScript version does @anthropic-ai/sdk require?
TypeScript 4.7 or later for correct generic inference. The SDK ships its own .d.ts files so you get full type coverage without @types/* packages.
How do I type the response from client.messages.create?
The return type is Message from @anthropic-ai/sdk/resources/messages. response.content is ContentBlock[] — a discriminated union of TextBlock and ToolUseBlock — so use if (block.type === 'text') to narrow the type.
How do I pass a typed system prompt with prompt caching?
Use type TextBlockParam (imported from @anthropic-ai/sdk/resources/messages) and add cache_control: { type: 'ephemeral' } to the block. Pass an array of TextBlockParam to the system field instead of a string.
Is there a TypeScript example for streaming tool use?
Yes. Subscribe to the stream and filter for content_block_start events where content_block.type === 'tool_use' to catch tool invocations, and content_block_delta events where delta.type === 'input_json_delta' to receive streamed tool arguments as partial JSON.

Free tools

Cost Calculator → Prompt-Pricing Recommender → Diff Summarizer → Skills Browser →

Related

Claude Opus 4.7 vs Sonnet 4.6 Pricing (2026 Comparison)How Much Does Claude Cost? (2026 API Pricing Guide)Claude Prompt Caching: 90% Cost Savings Explained (2026)Claude API Cost Calculator: Estimate Your Anthropic BillClaude vs GPT-4 Pricing: 2026 API Cost Comparison