繁体   English   中英

Object 值到 Enum 或类型

[英]Object values to Enum or type

我有一个 object 作为:

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

我后来使用了 object 作为

type PartType = "hand"| "mouth"

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

但我想从PartType的值中提取bodyParts 有什么解决方法吗? 或者也许从 object 创建枚举并将类型设置为枚举。 我尝试寻找创建枚举但没有找到解决方案。 我可以创建枚举,但我想自动化创建枚举的任务,因为可以添加正文部分。

我怀疑对您的最终目标有更广泛的了解,可以建议使用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,
    },
];

游乐场链接

或者如果我们获取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,
    },
];

游乐场链接

但是,如果你想保留它们的编译时类型(特别是要确保data是一个元组,而不仅仅是一个数组),你可以使用const断言和不太明确的类型做得更好:

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

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

游乐场链接

暂无
暂无

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

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