Here是此问题的 TypeScript Playground 示例,它仅具有此问题所需的最低限度。
这是出现这种情况的现实示例: 我有一个枚举
export enum OrderType {
Market = 'MARKET',
Limit = 'LIMIT',
}
然后我有一个输入字段
export const TypeInputInner = ({ onChange, value }: Props) => {
return (
<Select style={{ width: 150, margin: 5 }} value={value} onChange={onChange}>
{Object.keys(OrderType).map(type => (
<Option key={type} value={OrderType[type]}>
{type}
</Option>
))}
</Select>
);
};
该 OrderType[type]
部分存在 TS 错误:
Error:(16, 45) TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
这是为什么呢?枚举不就是一个对象吗?即
{
Market: "MARKET",
Limit: "LIMIT"
}
数字从何而来?
顺便说一句,我知道如果我使用type as any
,TS 错误就会消失。
最佳答案
主要问题是 the return type of Object.keys(obj)
is string[]
and not Array<keyof typeof obj>
。这是期望的和预期的行为,因为 TypeScript 无法确定对象仅它所知道的键。
如果您确定您的对象中只有已知的键,那么您可以使用 type assertion告诉编译器它可以处理 Object.keys()
作为一个更受限制的集合,如:
(Object.keys(OrderType) as Array<keyof typeof OrderType>).map(type =>
console.log(OrderType[type]) // okay now
);
它提示的原因是type
不是number
可能是因为enum
类型有 numeric index为了实现reverse mappings对于任何 numeric枚举中的值。当然这里的例子纯粹是一个string enum但我猜他们在每个枚举对象类型上都放置了数字索引:🤷
const hmm = OrderType[123]; // string 🤔
无论如何,当 type
只是 string
, OrderType[type]
是 any
因为没有字符串索引签名,并且编译器警告对象上唯一的索引签名是数字。
好的,希望有帮助;祝你好运!
关于typescript - 当使用enum作为对象时, "Element implicitly has an ' any'类型,因为索引表达式不是类型 'number'”,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57137471/