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


当前回答

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

1)制作界面

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

2)打印一份

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

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

<input customProp={copy} />

其他回答

类似于@Piotr Lewandowski的回答,但在forEach中:

const config: MyConfig = { ... };

Object.keys(config)
  .forEach((key: keyof MyConfig) => {
    if (config[key]) {
      // ...
    }
  });

另一种避免错误的方法是像这样使用强制转换:

let secondValue: string =(<任意>someObject)[key]; (注意括号)

唯一的问题是,这不再是类型安全的,因为您正在强制转换为任何。但是您总是可以转换回正确的类型。

ps:我使用的是typescript 1.7,不确定以前的版本。

目前更好的解决方案是声明类型。就像

enum SomeObjectKeys {
    firstKey = 'firstKey',
    secondKey = 'secondKey',
    thirdKey = 'thirdKey',
}

let someObject: Record<SomeObjectKeys, string> = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   'thirdValue',
};

let key: SomeObjectKeys = 'secondKey';

let secondValue: string = someObject[key];

像这样声明对象。

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

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

1)制作界面

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

2)打印一份

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

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

<input customProp={copy} />