我总是用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];

需要注意的是,这里的思想是键变量来自应用程序中的其他地方,可以是对象中的任何键。

我已经尝试通过以下方式显式地转换类型:

let secondValue: string = <string>someObject[key];

或者我的场景只是不可能与-noImplicitAny?


当前回答

上面提到的“keyof”解决方案是有效的。但如果变量只使用一次,例如循环遍历一个对象等,你也可以对它进行类型转换。

for (const key in someObject) {
    sampleObject[key] = someObject[key as keyof ISomeObject];
}

其他回答

像这样声明对象。

export interface Thread {
    id:number;
    messageIds: number[];
    participants: {
        [key:number]: number
    };
}

导致

你只能在索引时使用类型,这意味着你不能使用const来进行变量引用:

例子

type Person = { age: number; name: string; alive: boolean };

const key = "age";
type Age = Person[key];

结果

Type 'any' cannot be used as an index type.

解决方案

使用类型来引用道具

例子

type key = "age";
type Age = Person[key];

结果

type Age = number

声明类型,它的键是字符串,值可以是任何 然后用这个类型声明对象,lint就不会显示出来

type MyType = {[key: string]: any};

所以你的代码会

type ISomeType = {[key: string]: any};

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

    let key: string = 'secondKey';

    let secondValue: string = someObject[key];

我能在3个步骤中使用Typescript 3.1找到的最简单的解决方案是:

1)制作界面

interface IOriginal {
    original: { [key: string]: any }
}

2)打印一份

let copy: IOriginal = (original as any)[key];

3)在任何地方使用(包括JSX)

<input customProp={copy} />

下面的tsconfig设置将允许您忽略这些错误—将其设置为true。

suppressImplicitAnyIndexErrors Suppress noimplicit任何索引对象缺乏索引签名的错误。