简体   繁体   中英

How to define a type of object with keys of values of enum

export const enum Enum1{
  key1='value1',
  key2='value2',
  key3='value3',
}

type ObjType = {
  [Key in keyof Enum1]: {
    some_object: number
  }
}

export const obj1:ObjType ={
  [Enum1.key1]:{some_object:123},
  [Enum1.key2]:{some_object:123},
  [Enum1.key3]:{some_object:123}
}

The above code produces an error:

Error:(145, 3) TS2322: Type '{ [Enum1.key1]: { some_object: number; }; [Enum1.key2]: { some_object: number; }; [Enum1.key3]: { some_object: number; }; }' is not assignable to type 'Obj'. Object literal may only specify known properties, and '[Enum1.key1]' does not exist in type 'Obj'.

I would like to define a type ( ObjType ) that its keys are all the values of the Enum1 enum.

How can I do that? If it's not possible, what is the correct way to enforce that obj1 keys contains all Enum1 values?

You are close. You don't want keyof Enum1 . keyof Enum1 would be essentially keyof an enum value, and since this a string enum it would be keyof string . The Enume1 type can be seen as a union of all enum memebers, so you can just use that:

export const enum Enum1{
  key1='value1',
  key2='value2',
  key3='value3',
}

type ObjType = {
  [Key in Enum1]: {
    some_object: number
  }
}

export const obj1:ObjType ={
  [Enum1.key1]:{some_object:123},
  [Enum1.key2]:{some_object:123},
  [Enum1.key3]:{some_object:123}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM