Skip to content

Instantly share code, notes, and snippets.

@adesurirey
Created July 29, 2020 23:42
Show Gist options
  • Save adesurirey/f2a847138abf3c7e8e04420cd4470854 to your computer and use it in GitHub Desktop.
Save adesurirey/f2a847138abf3c7e8e04420cd4470854 to your computer and use it in GitHub Desktop.
Centralizing routes declaration and usage in a React app
const ROUTES = {
SHIPMENTS: "/shipments",
SHIPMENT: "/shipments/:id",
};
interface RouteParams {
SHIPMENT: { id: number };
}
type Routes = typeof ROUTES;
type Route = keyof Routes;
type DynamicRoute = keyof RouteParams;
type StaticRoute = keyof Omit<Routes, keyof RouteParams>;
interface BuildPath {
<T extends DynamicRoute>(route: T, params: RouteParams[T]): string;
<T extends StaticRoute>(route: T): string;
}
const buildPath: BuildPath = (route: Route, params: any = {}) => {
const routeElements = ROUTES[route].split("/");
return routeElements.reduce((prevElement, currentElement) => {
const nextElement = currentElement.startsWith(":")
? params[currentElement.slice(1)]
: currentElement;
return `${prevElement}/${nextElement}`;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment