Skip to content

Instantly share code, notes, and snippets.

@strlns
Last active March 12, 2023 21:51
Show Gist options
  • Save strlns/8c8f7fd0d6438c89392337fa4cbc5fe1 to your computer and use it in GitHub Desktop.
Save strlns/8c8f7fd0d6438c89392337fa4cbc5fe1 to your computer and use it in GitHub Desktop.
createBrowserRouter with Intellisense suggestions / exhaustive union types for route IDs
import { RouterProvider } from "react-router";
import { createBrowserRouter } from "react-router-dom";
import { routes } from "routes";
function App() {
//...
const router = createBrowserRouter(routes);
import Home from "pages/Home";
import RouteError from "components/Error/RouteError";
import { RouteObject } from "react-router";
const ROUTES = [
{
path: "/",
element: <Home />,
errorElement: <RouteError />,
id: "Home",
},
//...
] as const;
//alternatively, just use
//export const routes = [...ROUTES].slice() as RouteObject[];
export const routes = [...ROUTES] as Mutable<typeof ROUTES> as RouteObject[];
type RouteID = (typeof ROUTES)[number]["id"];
type RoutePath = (typeof ROUTES)[number]["path"];
type RoutePaths = {
[key in RouteID]: RoutePath;
};
export const routePaths: RoutePaths = Object.fromEntries(
ROUTES.map((route) => [route.id, route.path])
) as RoutePaths;
type Mutable<T extends object> = {
-readonly [K in keyof T]: T[K];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment