简体   繁体   中英

Typescript - How can I dynamically define a type from an array of possible values?

I would like to find a way to dynamically define a type from an array of possibilities.

I have a map as shown below where the keys are the types's name, and the corresponding values are arrays of what that type can be.

export const typeOptions = {
  areaOfStudy: ["politics", "mathematics", "biology"],
  ageRange: ["1821", "2225", "26plus"],
  societyCategory: [
    "Debate Society",
    "Basketball Society",
    "Football Society",
    "3D Modelling Society",
  ],
}

I would like to find a way to infer from the object above the following:

export type AreaOfStudy = "politics" | "mathematics" | "biology";
export type AgeRange = "1821" | "2225" | "26plus";
export type SocietyCategory =
  | "Debate Society"
  | "Basketball Society"
  | "Football Society"
  | "3D Modelling Society"

Any ideas or tips on how I could do that?

You can use typeof combined with as const

typeof gives you the type of a value. as const says that it should use the exact values.

export const typeOptions = {
areaOfStudy: ["politics", "mathematics", "biology"] as const,
ageRange: ["1821", "2225", "26plus"] as const,
societyCategory: [
    "Debate Society",
    "Basketball Society",
    "Football Society",
    "3D Modelling Society",
] as const,
}

export type AreaOfStudy = typeof typeOptions.areaOfStudy[number]
export type AgeRange = typeof typeOptions.ageRange[number]
export type SocietyCategory = typeof typeOptions.societyCategory[number]

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