Typescript箭头函数返回对象的正确写法
Searched codebase for "const toOpenAiTools = (tools?: ToolDefinition[]) => tools?.map((tool) => ({ type: "function" as const, function: { name: tool.name, description: tool.description, parameters: tool.parameters, }, }));能写成这样的吗 const toOpenAiTools = (tools?: ToolDefinition[]) => tools?.map((tool) => { type: "function" as const, function: { name: tool.name, description: tool.description, parameters: tool.parameters, }, });", 13 results
不行。原因是箭头函数中 {} 会被识别为函数体,而不是对象字面量,里面的 type: "function" 会被当成 label 语句,不是对象属性,导致语法错误。
三种正确写法:
// ✅ 1. 用 () 包裹对象(现在的写法)
tools?.map((tool) => ({
type: "function" as const,
function: { ... },
}))
// ✅ 2. 用 {} 函数体 + 显式 return
tools?.map((tool) => {
return {
type: "function" as const,
function: { ... },
};
})
// ❌ 3. 你的写法 —— 语法错误
tools?.map((tool) => {
type: "function" as const, // 被当成 label,逗号报错
function: { ... },
})
记住: 箭头函数直接返回对象时,必须用 () 包裹,否则必须加 return。
