Use Enum as restricted key type in Typescript

前端 未结 3 1411
悲&欢浪女
悲&欢浪女 2021-02-05 01:19

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

3条回答
  •  我在风中等你
    2021-02-05 01:51

    Yes. Just type

    let layer:{[key in keyof typeof MyEnum]: any}
    

    The keyof keyword is available since Typescript 2.1. See the TypeScript documentation for more details. Using only keyof for enums wouldn't work (you'd get the keys of the enum type and not the enum constants), so you have to type keyof typeof.

提交回复
热议问题