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


当前回答

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

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

其他回答

TypeScript 2.1引入了优雅的方法来处理这个问题。

const key: (keyof ISomeObject) = 'secondKey';
const secondValue: string = someObject[key];

我们可以在编译阶段通过keyof关键字(参见changelog)访问所有对象属性名。

你只需要用keyof ISomeObject替换字符串变量类型。 现在编译器知道关键变量只允许包含来自ISomeObject的属性名。

完整的例子:

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

const someObject: ISomeObject = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   3
};

const key: (keyof ISomeObject) = 'secondKey';
const secondValue: string = someObject[key];

// You can mix types in interface, keyof will know which types you refer to.
const keyNumber: (keyof ISomeObject) = 'thirdKey';
const numberValue: number = someObject[keyNumber];

typescriptlang.org上的实时代码(设置noImplicitAny选项)

进一步阅读,了解更多用法要点。

添加索引签名将让TypeScript知道应该是什么类型。

在你的例子中,这将是[key: string]: string;

interface ISomeObject {
    firstKey:      string;
    secondKey:     string;
    thirdKey:      string;
    [key: string]: string;
}

但是,这也强制所有属性类型与索引签名匹配。因为所有的属性都是一个字符串,所以它可以工作。

虽然索引签名是描述数组和“字典”模式的强大方法,但它们也强制所有属性匹配它们的返回类型。

编辑:

如果类型不匹配,则可以使用联合类型[key: string]: string|IOtherObject;

对于联合类型,最好让TypeScript推断类型,而不是定义类型。

// Type of `secondValue` is `string|IOtherObject`
let secondValue = someObject[key];
// Type of `foo` is `string`
let foo = secondValue + '';

尽管如果索引签名中有很多不同的类型,这可能会有点混乱。另一种方法是在签名中使用any。[key: string]: any;然后需要像上面那样强制转换类型。

没有索引器?那就自己做吧!

我将其全局定义为定义对象签名的一种简单方法。如果需要,T可以是任何:

type Indexer<T> = { [ key: string ]: T };

我只是将indexer添加为类成员。

indexer = this as unknown as Indexer<Fruit>;

所以我的结论是:

constructor(private breakpointResponsiveService: FeatureBoxBreakpointResponsiveService) {

}

apple: Fruit<string>;
pear: Fruit<string>;

// just a reference to 'this' at runtime
indexer = this as unknown as Indexer<Fruit>;

something() {

    this.indexer['apple'] = ...    // typed as Fruit

这样做的好处是您可以得到正确的类型—许多使用<any>的解决方案将为您丢失输入。记住,这不会执行任何运行时验证。如果您不确定某个东西是否存在,您仍然需要检查它是否存在。

如果你想过于谨慎,并且你正在使用strict,你可以这样做来揭示所有你可能需要进行显式未定义检查的地方:

type OptionalIndexed<T> = { [ key: string ]: T | undefined };

我通常不认为这是必要的,因为如果我有来自某处的字符串属性,我通常知道它是有效的。

我发现,如果我有很多代码需要访问索引器,并且可以在一个地方更改类型,那么这个方法特别有用。

注意:我使用的是严格模式,未知是绝对必要的。

编译后的代码将是indexer = this,这与typescript为你创建_this = this非常相似。

类似于@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,不确定以前的版本。