Angular开发中用number索引Object报隐式any错误如何解决
问题原因
这个报错是TypeScript类型校验触发的,你为noteCountObj声明的通用Object类型没有明确指定允许的索引类型和值类型,当你用数字类型的noteId作为键访问对象属性时,类型系统无法识别该操作的合法性,因此抛出了隐式any类型错误。
修复方案
仅需要修改noteCountObj的类型声明即可,有两种常用写法:
- 写法1:使用索引签名明确类型
把原代码中的
let noteCountObj: Object = {};
替换为
let noteCountObj: { [key: number]: number } = {};
该声明明确告知TypeScript,这个对象的键是数字类型,值也是数字类型,完全匹配你的使用场景。
- 写法2:使用TS内置工具类型
Record(更简洁)
let noteCountObj: Record<number, number> = {};
Record<键类型, 值类型>是TypeScript提供的语法糖,效果和上面的索引签名完全一致。
可选优化
为了避免未出现在搜索结果中的笔记取值为undefined导致排序异常,可以在取值时增加默认值兜底:
let aCount = noteCountObj[aId] ?? 0; let bCount = noteCountObj[bId] ?? 0;
完整修复后代码
sortByRelevancy(searchResults: Note[]) { // This method will calculate the relevancy of a note based on the number of times it appears in // the search results let noteCountObj: Record<number, number> = {}; // 仅修改了这一行的类型定义 searchResults.forEach(note => { let noteId = this.service.getId(note); if (noteCountObj[noteId]) { noteCountObj[noteId] += 1; } else { noteCountObj[noteId] = 1; } }); this.filteredNotes = this.filteredNotes.sort((a: Note, b: Note) => { let aId = this.service.getId(a); let bId = this.service.getId(b); let aCount = noteCountObj[aId] ?? 0; let bCount = noteCountObj[bId] ?? 0; return bCount - aCount; }); }
内容的提问来源于stack exchange,提问作者user16814898
相关产品推荐
相关产品推荐

