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

Time:01-27

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'

CodePudding user response:

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"];
  •  Tags:  
  • Related