Use Enum as restricted key type in Typescript

前端 未结 3 1416
悲&欢浪女
悲&欢浪女 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 02:06

    Short Answer:

    let layer: Partial>;
    

    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>;
    

    :)

提交回复
热议问题