Reputation: 75
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!
Upvotes: 2
Views: 1303
Reputation: 249506
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]
Upvotes: 3