typescript - 在启用 noImplicitAny 标志的情况下编译 typescript 时,如何防止错误 "Index signature of object type implicitly has an ' any' type"?

标签 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];

需要注意的重要一点是,关键变量来自应用程序中的其他地方,并且可以是对象中的任何键。

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

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

或者我的场景无法使用 --noImplicitAny

最佳答案

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

在你的情况下是 [key: string]: string;

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

但是,这也强制所有属性类型匹配索引签名。由于所有属性都是一个 string,因此它可以正常工作。

While index signatures are a powerful way to describe the array and 'dictionary' pattern, they also enforce that all properties match their return type.

编辑:

如果类型不匹配,可以使用联合类型[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; 然后你需要像上面那样转换类型。

关于typescript - 在启用 noImplicitAny 标志的情况下编译 typescript 时,如何防止错误 "Index signature of object type implicitly has an ' any' type"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32968332/

相关文章:

reactjs - 如何为使用参数调用 React setState 的函数创建 TypeScript 类型?

Angular 6 : Cannot set property of undefined

typescript - 如何在 Typescript 中获取枚举大小作为类型

来自@types 中声明的命名空间的 typescript 扩展接口(interface)

javascript - 如何映射对象数组并将它们作为按 "categories"排序的新对象数组返回

javascript - 在 Angular 2 中单击按钮时如何将焦点设置到 div?

typescript - 如何使用 Typescript 和 Webpack 对类使用 tree-shaking?

typescript - 在 yarn 工作区的子包中找不到 Jest

typescript - 返回时保持滚动位置并更改路线角度5

javascript - 使用 Angular 6 上传 JSON 文件