使用Lodash _.map处理JSON数组时出现TypeScript类型错误求助
解决Lodash map处理JSON数组时的TypeScript类型错误
我之前用过_.map(users, 'id')成功从对象数组提取指定字段,但导入包含349000+条美国邮编、城市、州、县信息的JSON数组citystatezip后,尝试用_.map(citystatezip, 'zip_code')提取zip_code字段时,触发了以下TypeScript错误:
No overload matches this call. The last overload gave the following error. Argument of type '{}' is not assignable to parameter of type 'Dictionary<unknown> | NumericDictionary<unknown> | null | undefined'.ts(2769) collection.d.ts(1180, 9): The last overload is declared here.
相关代码
- 导入语句:
import * as citystatezip from 'src/assets/json/city-state-zip-county.json';
- 处理方法:
getAllZipCodes(): any { this.allzipcodes = _.map(citystatezip, 'zip_code'); }
- JSON数组示例片段:
[ { "zip_code": 43616, "latitude": 41.656948, "longitude": -83.44433, "city": "Oregon", "state": "OH", "county": "Lucas" } ]
问题原因
TypeScript默认会把导入的JSON文件推断为{}(普通对象)类型,但你的JSON实际是数组结构。Lodash的_.map方法对数组和对象有不同的类型重载,类型不匹配就导致了报错。
解决办法
1. 显式定义类型并断言
先定义JSON元素的接口,再给导入的JSON指定类型:
// 定义邮编信息的类型接口 interface ZipInfo { zip_code: number; latitude: number; longitude: number; city: string; state: string; county: string; } // 导入并指定类型 import * as citystatezip from 'src/assets/json/city-state-zip-county.json'; getAllZipCodes(): number[] { // 断言为数组类型 this.allzipcodes = _.map(citystatezip as ZipInfo[], 'zip_code'); return this.allzipcodes; }
2. 直接临时类型断言
如果不想定义完整接口,也可以在调用_.map时直接断言类型:
getAllZipCodes(): any { this.allzipcodes = _.map(citystatezip as Array<{zip_code: number}>, 'zip_code'); }
3. 调整导入方式并开启JSON模块解析
修改导入为默认导入,同时确保TypeScript配置文件tsconfig.json中compilerOptions.resolveJsonModule设为true:
// 默认导入 import citystatezip from 'src/assets/json/city-state-zip-county.json'; getAllZipCodes(): number[] { this.allzipcodes = _.map(citystatezip, 'zip_code'); return this.allzipcodes; }
内容的提问来源于stack exchange,提问作者Peter The Angular Dude
相关产品推荐
相关产品推荐

