在 Typescript 中使用 Enum 作为受限键类型 [英] Use Enum as restricted key type in Typescript
本文介绍了在 Typescript 中使用 Enum 作为受限键类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题是枚举可以用作键类型,而不仅仅是数字"或字符串"?目前似乎唯一可能的声明是 x:{[key:number]:any} ,其中键可以是数字"或字符串"类型.是否可以在此示例中进行类似操作:
The question is can enum be used as a key type instead of only "number" or "string" ? Currently it seems like the only possible declaration is x:{[key:number]:any} where key can be of type "number" or "string". Is it possible to make something like in this example:
示例:
enum MyEnum
{
First,
Second
}
var layer:{[key:MyEnum]:any};
推荐答案
自 2018 年, 在 Typescript 中有更简单的方法,无需使用 keyof typeof
:
Since 2018, there is an easier way in Typescript, without using keyof typeof
:
let layer: { [key in MyEnum]: any}
不必包含所有键:
let layer: { [key in MyEnum]?: any}
这篇关于在 Typescript 中使用 Enum 作为受限键类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文