Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save airtonix/8b12279149e6df25e616b385b218218a to your computer and use it in GitHub Desktop.
Save airtonix/8b12279149e6df25e616b385b218218a to your computer and use it in GitHub Desktop.
export {};
type RouteConfig = {
pathname: string;
redirect?: {
pathname: string;
};
};
type ExtractPathnames<Routes extends Record<string, RouteConfig>> = {
[K in keyof Routes]: Routes[K]['pathname'];
}[keyof Routes];
type ValidateRedirects<
Routes extends Record<string, RouteConfig>,
AllPathnames
> = {
[K in keyof Routes]: Routes[K] extends {
redirect: { pathname: string };
}
? Routes[K] extends {
redirect: { pathname: infer P };
}
? P extends AllPathnames
? Routes[K]
: never
: never
: Routes[K];
};
function createRoutes<Routes extends Record<string, RouteConfig>>(
routes: ValidateRedirects<Routes, ExtractPathnames<Routes>>
): Routes {
return routes;
}
function getRoutePaths<Routes extends Record<string, RouteConfig>>(
routes: Routes
): ExtractPathnames<Routes>[] {
return [];
}
// Usage
const RouteHashMap = createRoutes({
a: {
pathname: '/a',
redirect: {
pathname: 'f', // <<<< SHOULD FAIL. BUT DOES NOT T_T
},
},
b: {
pathname: '/b',
},
c: {
pathname: '/a/b/c',
},
old_c: {
pathname: '/c',
},
d: {
pathname: '/d',
},
} as const);
const RoutePathnames = getRoutePaths(RouteHashMap);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment