TypeScript SDK Quick Start
Get up and running with the @anthropic-ai/claude-code TypeScript SDK in just a few minutes.
Prerequisites
- Node.js 18+ required (20+ recommended)
- TypeScript 4.9+ supported
Installation
Global CLI Installation
npm install -g @anthropic-ai/claude-codeProject SDK Installation
npm install @anthropic-ai/claude-code
npm install --save-dev @types/node typescriptAuthentication
Choose one of these authentication methods:
Option 1: Anthropic API Key (Recommended)
export ANTHROPIC_API_KEY="your-api-key-here"Get your API key from the Anthropic Console.
Option 2: OAuth Token (for Pro/Max users)
claude setup-tokenOption 3: Third-Party Providers
- Amazon Bedrock: Set
CLAUDE_CODE_USE_BEDROCK=1 - Google Vertex AI: Set
CLAUDE_CODE_USE_VERTEX=1
Basic Usage
Your First Query
import { query, type SDKMessage } from "@anthropic-ai/claude-code";
async function main() {
const messages: SDKMessage[] = [];
for await (const message of query({
prompt: "Write a TypeScript function that validates email addresses",
abortController: new AbortController()
})) {
messages.push(message);
// Handle different message types
switch (message.type) {
case 'assistant':
console.log("Claude:", message.data.message.content);
break;
case 'result':
console.log(`\nCompleted in ${message.data.total_time_ms}ms`);
console.log(`Cost: $${message.data.total_cost_usd}`);
break;
}
}
}
main().catch(console.error);Understanding the Response
The SDK returns an async iterable stream of messages:
- System Message: Initialization info and available tools
- User Message: Echoes your prompt
- Assistant Message: Claude’s responses
- Result Message: Final message with cost and timing data
TypeScript Configuration
Create a tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"lib": ["ES2022"],
"types": ["node"],
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}Common Use Cases
Code Generation
const messages = await query({
prompt: "Create a React component for a todo list with TypeScript",
options: { maxTurns: 1 }
});Code Review
const messages = await query({
prompt: `Review this code for bugs and improvements:\n${codeToReview}`,
options: {
maxTurns: 1,
systemPrompt: "You are a senior TypeScript developer performing a code review."
}
});With AbortController
const controller = new AbortController();
// Cancel after 30 seconds
setTimeout(() => controller.abort(), 30000);
for await (const message of query({
prompt: "Analyze this large codebase",
abortController: controller
})) {
// Process messages
}Quick Tips
- Always handle errors: Wrap queries in try-catch blocks
- Use AbortController: For cancellable operations
- Monitor costs: Check the
total_cost_usdfield - Type safety: Use the provided TypeScript types
Common Issues
Authentication Failed
# Check if API key is set
echo $ANTHROPIC_API_KEY
# Set it if missing
export ANTHROPIC_API_KEY="sk-ant-..."Permission Errors (npm)
# Fix with migrate-installer
claude migrate-installer
# Or configure npm to use user directory
mkdir ~/.npm-global
npm config set prefix ~/.npm-global
export PATH=~/.npm-global/bin:$PATH