简体   繁体   中英

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.

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

const QuestionnaireOptions = {
    GENDER_OPTIONS: ["female", "male"],
    SIZE_OPTIONS: [
        "s",
        "m",
        "l",
    ],
};

type Gender = ?? 

I could not find any resource / similar stackoverflow post so far.

Thanks for your time!

You can use a index access type to get a specific property of the container object:

const QuestionnaireOptions = {
    GENDER_OPTIONS: ["female", "male"],
    SIZE_OPTIONS: [
        "s",
        "m",
        "l",
    ],
} as const;

type Gender = typeof QuestionnaireOptions['GENDER_OPTIONS'][number]

Playground Link

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