Use Enum as restricted key type in Typescript

前端 未结 3 1410
悲&欢浪女
悲&欢浪女 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.

    0 讨论(0)
  • 2021-02-05 01:56

    For those who are seeking for a way to get the keys of the enum instead its value, you just need to change from this:

    type myType = Partial<Record<MyEnum, number>>;
    

    to that:

    type myType = Partial<Record<keyof typeof MyEnum, number>>;
    
    0 讨论(0)
  • 2021-02-05 02:06

    Short Answer:

    let layer: Partial<Record<MyEnum, any>>;
    

    Long Answer (with details):

    I had the same problem. I wanted to have the following piece of code work.

    enum MyEnum {
        xxx = "xxx",
        yyy = "yyy",
        zzz = "zzz",
    }
    
    type myType = ...; // Fill here
    
    const o: myType = { // keys should be in MyEnum, values: number
       [MyEnum.xxx]: 2,
       "hi": 5, // <--- Error: complain on this one, as "hi" is not in enum
    }
    
    o[MyEnum.yyy] = 8; // Allow it to be modified later
    
    

    Starting from the other answer on this question, I got to:

    type myType = {[key in keyof typeof MyEnum]: number};
    

    But it would nag that o is missing "yyy". So I needed to tell it that the object is going to have some of the enum keys, not all of them. So I got to add ? to get:

    type myType = {[key in keyof typeof MyEnum]?: number};
    

    It was working fine, until I added the line at the end of the code to modify the object after its first creation. Now it was complaining that the type inherited through keyof has its properties as readonly and I cannot touch them after the first creation! :| In fact, hovering over myType in Typescript Playground, it will be shown as:

    type myType = {
        readonly xxx?: number | undefined;
        readonly yyy?: number | undefined;
        readonly zzz?: number | undefined;
    }
    

    Now, to remove that unwanted readonly, I found that I can use:

    type myType = {-readonly [key in keyof typeof myEnum1]?: number };
    

    Quite ugly, but working!

    Until I played with Typescript Utility Types, and found what I wanted!

    type myType = Partial<Record<MyEnum, number>>;
    

    :)

    0 讨论(0)
提交回复
热议问题