gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:13:48 24 4
gpt4 key购买 nike

我总是使用标志 --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/48281768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com