TypeScript safe route names?

Viewed 226

Consider the following code:

const router = useRouter()

await router.push({
  name: 'NonExistingRoute', // no typescript error ):
}) 

A non existing route name was given, but no TypeScript error happens. Instead the issue will only be noticed on runtime. Any way to get a compile-time error on this?

3 Answers

Perhaps you could wrap this in a utility function that only accepts typed route strings

const router = useRouter()
export type NamedRoute = "login" | "logout" | "user-profile";

export async function goToNamedRoute(name: NamedRoute): Promise<void> {
    return router.push({name});
}

In short no.

For a compile error to exist there would need to be something explicitly wrong with the code, referencing an non-existent file, syntax error, etc.

It does sound like you are trying to solve some other issue here...i.e. why do you have the names of non-existing routes in your app?

In any case, perhaps you can avoid your errors programmatically, e.g.

 let r = router.resolve({name: 'NonExistingRoute'});
 if (r.resolved.matched.length > 0){
    // exists
 } else {
    // doesn't exist
 }

If you want to rely on Typescript for detecting wrong routes you might just use enums or closed types maybe?, although that will surely require some composition. Probably one way to go could be:

enum Cities {
   NY, 
   London
}

function routeCreator(city: Cities, restOfPath?: string){
    //combine paths somehow, e.g.
    if(!restOfPath) return `/${Cities[city]}/`;
    return `/${Cities[city]}/${restOfPath}`
}

Related