2

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!

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I think worth adding docs link
Missed to answer, thank you!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.