【问题标题】:Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'Object'元素隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引“对象”类型
【发布时间】:2022-01-04 12:08:44
【问题描述】:

您好,我正在学习 Angular,并尝试按照 YouTube 上的 Note Mates 教程进行操作,我几乎完成了,但这对我不起作用。我应该按相关性进行排序,我在这里有这段代码,我得到的 Element 隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引 noteCountObj[noteId] 的“对象”类型错误。

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;
    });
}

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

【问题讨论】:

  • noteId的类型是什么?这是字符串还是数字?

标签: angular typescript error-handling


【解决方案1】:

这是因为您的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 = {};

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2021-08-08
    • 1970-01-01
    • 2021-03-17
    • 2021-10-19
    • 2021-04-20
    • 1970-01-01
    • 2020-08-24
    • 2020-11-13
    相关资源
    最近更新 更多