相关疑难解决方法(0)

在编译带有noImplicitAny标志的typescript时,如何防止错误"对象类型的索引签名隐式具有'任何'类型"?

我总是使用标志--noImplicitAny编译Typescript.这是有道理的,因为我希望我的类型检查尽可能紧.

我的问题是,使用以下代码我得到错误Index signature of object type implicitly has an 'any' type:

interface ISomeObject {
    firstKey:   string;
    secondKey:  string;
    thirdKey:   string;
}

let someObject: ISomeObject = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   'thirdValue'
};

let key: string = 'secondKey';

let secondValue: string = someObject[key];
Run Code Online (Sandbox Code Playgroud)

需要注意的重要一点是,关键变量来自应用程序中的其他位置,可以是对象中的任何键.

我试过通过以下方式明确地转换类型:

let secondValue: string = <string>someObject[key];
Run Code Online (Sandbox Code Playgroud)

或者我的情景是不可能的--noImplicitAny

typescript

285
推荐指数
11
解决办法
16万
查看次数

标签 统计

typescript ×1