简体   繁体   English

将枚举分配为 object 类型的键的值

[英]Assign an enum as the value of the key of an object type

Below is my Enum:下面是我的枚举:

export enum MyEnum {
  Enum1 = 'Enum 1',
  Enum2 = 'Enum 2',
  Enum3 = 'Enum 3',
  Enum4 = 'Enum 4',
  Enum5 = 'Enum 5',
}

I want to create a type for the example object shown below:我想为示例 object 创建一个类型,如下所示:

const testData = {
  test1: {
    Enum1 = 'Enum 1',
    Enum2 = 'Enum 2',
  },
  test2: {
    Enum1 = 'Enum 1',
    Enum2 = 'Enum 2',
    Enum3 = 'Enum 3',
    Enum4 = 'Enum 4',
  },
  test2: {
    Enum1 = 'Enum 1',
    Enum2 = 'Enum 2',
    Enum4 = 'Enum 4',
  },
};

So far, I could come up with:到目前为止,我可以想出:

type FilteredBuyableMethods = {
  [key: string]: Partial<{
    [key in MyEnum]: string
  }>
};

How can I replace the string in [key in MyEnum]: string with the exact value of the key?如何用键的确切值替换[key in MyEnum]: string string的字符串?

So if the key is Enum1 , the value for it should only be 'Enum 1' and so on.所以如果键是Enum1 ,它的值应该只是 'Enum 1' 等等。 Thanks in anticipation.感谢期待。

Using the tricks from Use Enum as restricted key type in Typescript and Typescript: string literal union type from enum , you can construct a mapped type as follows:使用Use Enum as restricted key type in TypescriptTypescript: string literal union type from enum中的技巧,您可以构造如下映射类型:

type FilteredBuyableMethods = {
  [key: string]: Partial<{
    [key in keyof typeof MyEnum]: `${typeof MyEnum[key]}`
  }>
};

Notice the typeof MyEnum[key] parses as (typeof MyEnum)[key] .注意typeof MyEnum[key]解析为(typeof MyEnum)[key]
( online playground ) 网上游乐场

This will both prevent wrong keys (that are not keys of the enum), as well as wrong value (that don't fit to their key respectively).这既可以防止错误的键(不是枚举的键),也可以防止错误的值(分别不适合它们的键)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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