【问题标题】:How to FIX implicit any of array access of property如何修复隐式任何属性的数组访问
【发布时间】:2021-02-23 11:56:58
【问题描述】:

我有这个代码:

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 以获得更简洁的代码,但是设置此属性的简洁方法是什么?

【问题讨论】:

    标签: typescript tsconfig


    【解决方案1】:

    你可以声明一个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
    }
    
    

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      相关资源
      最近更新 更多