Use Enum as restricted key type in Typescript

Since 2018, there is an easier way in Typescript, without using keyof typeof:

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

To not have to include all keys:

let layer: { [key in MyEnum]?: any}

Short Answer:

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

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<keyof typeof MyEnum, number>>;

:)


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.

Tags:

Typescript