본문 바로가기
C.W.K.
Stream
Lesson 01 of 06 · published

TypeScript SDK의 내보낸 타입을 그대로 써

~14 min · install, types, esm, cjs

Level 0Observer
0 XP0/64 lessons0/13 achievements
0/150 XP to next level150 XP to go0% complete

공식 패키지 하나가 여러 모듈 형식을 품어

@anthropic-ai/sdk는 ESM과 CommonJS를 모두 제공하며 Node·Bun·Deno·Edge에서 쓸 수 있어. 런타임마다 제약은 있지만 다른 비공식 포장 패키지를 찾을 필요는 없어. 프로젝트의 모듈 방식에 맞는 import를 고르면 돼.

메시지 모양을 손으로 다시 만들지 마

요청과 응답 타입이 모두 공개돼 있어. 메시지 입력에는 Anthropic.MessageParam, 완성된 응답에는 Anthropic.Message, 콘텐츠 블록에는 Anthropic.TextBlockAnthropic.ToolUseBlock을 써. SDK 타입을 따르면 잘못된 도우미 콘텐츠나 도구 결과를 컴파일 단계에서 잡을 수 있어.

클라이언트는 비동기 하나면 돼

Python과 달리 TypeScript SDK는 비동기 클라이언트 하나를 제공해. Node 서버, Next.js Route Handler, 작업자에서 같은 방식으로 호출할 수 있어. 생성자는 ANTHROPIC_API_KEY를 환경에서 읽으므로 호출마다 자격 증명을 넘길 필요가 없고, 키를 회전해야 하는 특별한 경우에만 명시해.

원칙: SDK가 내보낸 타입을 경계 계약으로 써. 메시지 구조를 복사해 다시 정의하면 실제 API와 언젠가 갈라져.

Code

설치와 검증·bash
npm install @anthropic-ai/sdk
# 또는: pnpm add @anthropic-ai/sdk / yarn add @anthropic-ai/sdk

# 검증
node -e "console.log(require('@anthropic-ai/sdk/package.json').version)"
node --input-type=module -e "import Anthropic from '@anthropic-ai/sdk'; const c = new Anthropic(); console.log(typeof c.messages.create);"
Typed Messages 호출 (모던 import)·typescript
import Anthropic from '@anthropic-ai/sdk';
import type { MessageParam, Message } from '@anthropic-ai/sdk/resources/messages';

const client = new Anthropic();

const messages: MessageParam[] = [
  { role: 'user', content: 'One sentence on why typed SDKs reduce production bugs.' },
];

const response: Message = await client.messages.create({
  model: 'claude-sonnet-4-6',
  max_tokens: 256,
  system: 'Answer in exactly one sentence.',
  messages,
});

const firstText = response.content.find(b => b.type === 'text');
if (firstText && firstText.type === 'text') {
  console.log(firstText.text);
}

External links

Exercise

TypeScript 프로젝트에 SDK를 넣고 사용자 문자열을 받아 타입이 있는 문자열 답을 돌려주는 함수를 만들어. 처음부터 끝까지 내보낸 타입을 쓰고 anyas Message는 쓰지 마.
Hint
as로 밀어붙이고 싶을 때는 먼저 콘텐츠 합집합을 type으로 좁혀.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.