首页 > 解决方案 > 如何修复隐式任何属性的数组访问

问题描述

我有这个代码:

function getKey(): string {
    return 'foo';
}

function dummy(): void {
    const object = {};
    const key: string = getKey();
    const value: any = 42;

    object[key] = value; // ERROR: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
}

我知道存在错误,因为我启用了noImplicitAny更清晰的代码,但是设置此属性的干净方法是什么?

标签: typescripttsconfig

解决方案


您可以声明一个Record类型:

function getKey(): string {
    return 'foo';
}

function dummy(): void {
    const object: Record<string, any> = {}; // Here you can define the type of value, example string or number.
    const key: string = getKey();
    const value: any = 42;

    object[key] = value; // Not error
}


推荐阅读