[英]Typescript create string literal union type from array in object
my goal is to create a string literal union type from an array in an object.我的目标是从 object 中的数组创建字符串文字联合类型。
I know how to create a union type from an array, like so我知道如何从数组创建联合类型,就像这样
const genderArr = ["female", "male"] as const;
type Gender = typeof genderArr[number]; // "female" | "male"
How can I achieve the same for an array inside of an object如何为 object 内部的数组实现相同的效果
const QuestionnaireOptions = {
GENDER_OPTIONS: ["female", "male"],
SIZE_OPTIONS: [
"s",
"m",
"l",
],
};
type Gender = ??
I could not find any resource / similar stackoverflow post so far.到目前为止,我找不到任何资源/类似的 stackoverflow 帖子。
Thanks for your time!谢谢你的时间!
You can use a index access type to get a specific property of the container object:您可以使用索引访问类型来获取容器 object 的特定属性:
const QuestionnaireOptions = {
GENDER_OPTIONS: ["female", "male"],
SIZE_OPTIONS: [
"s",
"m",
"l",
],
} as const;
type Gender = typeof QuestionnaireOptions['GENDER_OPTIONS'][number]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.