-
-
Save mselmany/ff57c7b1c8ee0ddac1f4fcc642b3aa6d to your computer and use it in GitHub Desktop.
routes.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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