元素隐式具有'any'类型,因为类型 'number' 的表达式不能用于索引类型"对象"



嗨,我正在学习Angular,并试图在YouTube上学习Note Mates教程,我几乎完成了,但这件事对我来说不起作用。我应该根据相关性进行排序,我在这里有这个代码,我得到Element隐式地有一个"any"类型,因为类型为"number"的表达式不能用于为noteCountObj[noteId]的类型为"Object"的错误编制索引。

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: Object = {}; // format - key:value => NoteId:number (note object id : count)
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];
let bCount = noteCountObj[bId];
return bCount - aCount;
});
}

我怎样才能做到这一点?谢谢你的帮助。

这是因为tsconfig.json中有strict: true(尽管如此,这还是一件好事(。然而,这样做会让编译器告诉你;把所有的东西(正确地(打出来";!

实际上是编译器选项noImplicitAny设置为true,但很可能您的配置中有strict: true。但是后一个选项启用了许多较小的选项,这使得键入更加严格

在您的案例中,您只是使用Object作为noteCountObj的类型,而实际上它是更具体的。尝试为noteCountObj键入以下内容:

const noteCountObj: Record<number, number> = {};

Record是来自typescript的一个方便的实用函数:

构造属性键为keys、属性值为type的对象类型。此实用程序可用于将一个类型的属性映射到另一个类型。

另一种键入方式是:

const noteCountObj: {[noteId: number]: number} = {};

在您的情况下,这可能是更具描述性的解决方案,其中术语noteId是任意选择的。它可以是你想要的任何东西。


如果你认为你会更频繁地使用这种对象类型,你可以从代码中提取它,把它放在一个单独的模型文件中,并执行以下操作:

export type IdCounter =  {[id: number]: number};

然后您可以导入并使用这种类型:

import type { IdCounter } from '../path/to/id-counter.model';
const noteCountObj: IdCounter = {};

最新更新