Type Error with onToolCall
When using the onToolCall
callback with TypeScript, you may encounter type errors when trying to pass tool properties directly to addToolResult
.
Problem
TypeScript cannot automatically narrow the type of toolCall.toolName
when you have both static and dynamic tools, leading to type errors:
// ❌ This causes a TypeScript errorconst { messages, sendMessage, addToolResult } = useChat({ async onToolCall({ toolCall }) { addToolResult({ tool: toolCall.toolName, // Type 'string' is not assignable to type '"yourTool" | "yourOtherTool"' toolCallId: toolCall.toolCallId, output: someOutput, }); },});
The error occurs because:
- Static tools have specific literal types for their names (e.g.,
"getWeatherInformation"
) - Dynamic tools have
toolName
as a genericstring
- TypeScript can't guarantee that
toolCall.toolName
matches your specific tool names
Solution
Check if the tool is dynamic first to enable proper type narrowing:
// ✅ Correct approach with type narrowingconst { messages, sendMessage, addToolResult } = useChat({ async onToolCall({ toolCall }) { // Check if it's a dynamic tool first if (toolCall.dynamic) { return; }
// Now TypeScript knows this is a static tool with the correct type addToolResult({ tool: toolCall.toolName, // No type error! toolCallId: toolCall.toolCallId, output: someOutput, }); },});