TypeScript调用map函数报错:father.map is not a function问题排查
问题分析与解决
核心错误点
- 变量赋值逻辑错误
你写的var father = parent;是把TypeScript的接口parent直接赋值给变量father,这完全不符合逻辑。正确的做法是将从JSON加载的单个parent类型的实例对象赋值给father,比如:
// 示例:解析JSON数据并赋值 const father: parent = JSON.parse(你的JSON数据字符串);
- 调用
map的对象错误father是单个parent对象,不是数组,而map是数组专属方法,所以会抛出father.map is not a function的错误。你需要遍历的是father对象里的addresses属性——这才是address类型的数组,每个元素都包含street属性。
正确代码示例
export interface parent{ fName: string; addresses: Array<address>; } export interface address{ street: string; city: string; state: string; zip: string; } // 模拟从JSON加载的父对象数据 const father: parent = { fName: "Dan", addresses: [ { street: "5th Avenue", city: "New York", state: "NY", zip: "10010" }, { street: "Sunset Boulevard", city: "Los Angeles", state: "CA", zip: "90028" } ] }; // 提取所有street属性组成数组 const streets = father.addresses.map(addr => addr.street); console.log(streets); // 输出: ["5th Avenue", "Sunset Boulevard"]
内容的提问来源于stack exchange,提问作者DanConsultant
相关产品推荐
相关产品推荐

