Skip to content

Instantly share code, notes, and snippets.

@DanielHoffmann
Created July 17, 2023 08:55
Show Gist options
  • Save DanielHoffmann/7cb21a6f716094df7a7499de8d16c04a to your computer and use it in GitHub Desktop.
Save DanielHoffmann/7cb21a6f716094df7a7499de8d16c04a to your computer and use it in GitHub Desktop.
routes.ts
import { createBrowserRouter, RouteObject } from 'react-router-dom'
const routes = [
myRoute1,
myRoute2,
myRoute3,
] satisfies RouteObject[]
type Route = {
[key: string]: any
readonly index?: boolean
readonly path?: string
children?: Route[]
}
// prefixes a "/" to T["path"] if "nested" is true
type PathsUnionHelper<T extends Route, nested extends boolean> = T['path'] extends string
? `${nested extends true ? '/' : ''}${T['path']}`
: ''
// extracts all route full-paths in the application
type PathsUnion<T extends Array<Route>, nested extends boolean> = T extends Array<infer U>
? U extends Route
? // routes that don't have "path" are ignored, including routes that are {index: true}
'path' extends keyof U
? // if "path" exists in Route then add it to the path list
| PathsUnionHelper<U, nested>
// if "children" exists in Route then go through the children recursively prefixing
// U["path"] to the childrens "path" and add them to the list as well
| `${PathsUnionHelper<U, nested>}${U extends { children: any }
? `${PathsUnion<U['children'], true>}`
: // if Route doesn't have children just add the same value again:
''}`
: never
: never
: never
// contains all routes paths, including nested routes ( routes[number].children[number].path )
export type RoutePaths = PathsUnion<typeof routes, false>
export browserRouter = createBrowserRouter(routes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment