简体   繁体   English

Object 值到 Enum 或类型

[英]Object values to Enum or type

I have a object as:我有一个 object 作为:

const bodyParts: Record<string, string>  = {
  HAND: 'hand',
  MOUTH: 'mouth'
}

I have used the object later as我后来使用了 object 作为

type PartType = "hand"| "mouth"

const data: Array<{part: 'hand' | 'mouth'}> = [{
  part: bodyParts[HAND]
}, {
  part: bodyParts[MOUTH]
}
]

But I want to extract PartType from values of bodyParts .但我想从PartType的值中提取bodyParts Is there any walkaround for this?有什么解决方法吗? Or maybe to create enum from object and set type as enum.或者也许从 object 创建枚举并将类型设置为枚举。 I tried looking for creating enum but didnot got to solution.我尝试寻找创建枚举但没有找到解决方案。 I can create Enum but I want to automate task of creation of enum, as bodyparts can be added.我可以创建枚举,但我想自动化创建枚举的任务,因为可以添加正文部分。

I suspect with a broader understanding of your end goal, one could suggest a better alternative to the use of bodyParts as shown in the question, but you can do what you want to do by inferring the type from the constant, like this:我怀疑对您的最终目标有更广泛的了解,可以建议使用bodyParts的更好替代方法,如问题所示,但您可以通过从常量推断类型来做您想做的事情,如下所示:

const bodyParts: Record<string, string> = {
    HAND: "hand",
    MOUTH: "mouth",
};

const data: Array<{ part: typeof bodyParts[keyof typeof bodyParts] }> = [
    {
        part: bodyParts.HAND,
    },
    {
        part: bodyParts.MOUTH,
    },
];

playground link 游乐场链接

Or it's a bit clearer if we grab an alias for typeof bodyParts :或者如果我们获取typeof bodyParts的别名会更清楚一些:

const bodyParts: Record<string, string> = {
    HAND: "hand",
    MOUTH: "mouth",
};
type BodyParts = typeof bodyParts;

const data: Array<{ part: BodyParts[keyof BodyParts] }> = [
    {
        part: bodyParts.HAND,
    },
    {
        part: bodyParts.MOUTH,
    },
];

playground link 游乐场链接

But , if you want to preserve the compile-time type of those (and in particular to ensure that data is a tuple, not just an array), you may do better with const assertions and less explicit typing:但是,如果你想保留它们的编译时类型(特别是要确保data是一个元组,而不仅仅是一个数组),你可以使用const断言和不太明确的类型做得更好:

const bodyParts = {
    HAND: "hand",
    MOUTH: "mouth",
} as const;

const data = [
    {
        part: bodyParts.HAND,
    },
    {
        part: bodyParts.MOUTH,
    },
] as const;

playground link 游乐场链接

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

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