TypeScript报错类型上不存在description属性 该如何修复排序接口数据的问题
报错原因
- 经过
map操作转换后,你得到的数组元素结构为{ label: string; value: string },你已经将原接口返回数据的description字段赋值给了新对象的label属性,转换后的对象本身不存在description属性 - TypeScript 静态类型检查识别到你在
sort回调中访问了不存在的属性,因此抛出类型错误
修复方案
将sort回调中访问的description替换为实际存在的label字段即可,推荐使用字符串的localeCompare方法实现排序,对中文、特殊字符的排序适配性更好,修复后代码如下:
getItemsTypes(): Observable<OptionModel[]> { const url = ApiUrlsConfig.risks.getItemsTypes(); return this.http.get<ResponseModel<ItemsType[]>>(url).pipe( map((response) => response.data.map((c) => ({ label: c.description, value: c.id })).sort((a, b) => a.label.localeCompare(b.label)) ) ); }
如果存在label为空的场景,可以加兜底逻辑避免报错:
.sort((a, b) => (a.label ?? '').localeCompare(b.label ?? ''))
内容的提问来源于stack exchange,提问作者lona bin
相关产品推荐
相关产品推荐

