Created
September 14, 2023 15:28
-
-
Save blakek/ac5203f46328e78833b9bbf98b3cc09f 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 enum KnownPaths { | |
GetHelp = "/app/get-help", | |
RunDetail = "/app/history/:runId" | |
} | |
/** Parses a string type into an object of route params */ | |
type ExtractRouteParams<T extends string> = string extends T | |
? Record<string, string> | |
: T extends `${infer _Start}:${infer Param}/${infer Rest}` | |
? { [K in Param | keyof ExtractRouteParams<Rest>]: string } | |
: T extends `${infer _Start}:${infer Param}` | |
? { [K in Param]: string } | |
: undefined; | |
export function getPath< | |
Path extends KnownPaths, | |
Params extends ExtractRouteParams<Path> | |
>(pathString: Path, ...[params]: Params extends undefined ? [] : [Params]): string { | |
if (params) { | |
return Object | |
.entries(params) | |
.reduce<string>((path, [key, value]) => | |
path.replace(`:${key}`, encodeURIComponent(value)), | |
pathString | |
) | |
} | |
return pathString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment