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'
>Solution :
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"];