0

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'

1 Answer 1

3

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"];
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the very quick answer @CertainPerformance yet it seems to result into a string type only and doesn't prevent me from passing wrong route names.
Like the answer says and the snippet shows, you need to type the array as const.
Correct, thanks for highlighting this detail to me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.