简体   繁体   中英

How to generate a type from an array of object value in Typescript

I am having an array of routes as such:

export const routes = [
  { name: 'Home', component: HomeScreen },
  { name: 'CreateProgram', component: CreateProgramScreen },
  { name: 'AddExercises', component: AddExercisesScreen },
]

I'd like to generate the kind of type alias as below programmatically from the name of the route:

type RouteNames = 'Home' | 'CreateProgram' | 'AddExercises'

Type the array as const so it doesn't get automatically widened, and then you can use [number] on its type to get a union of all object types, and then access ["name"] to get to type of the name property.

export const routes = [
  { name: 'Home', component: HomeScreen },
  { name: 'CreateProgram', component: CreateProgramScreen },
  { name: 'AddExercises', component: AddExercisesScreen },
] as const;
type RouteNames = (typeof routes)[number]["name"];

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