Created
June 20, 2024 00:24
-
-
Save airtonix/8b12279149e6df25e616b385b218218a to your computer and use it in GitHub Desktop.
This file contains 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
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