Created
September 29, 2023 12:10
-
-
Save a10y/ac9404dcd67933b94b819be2de2f6c63 to your computer and use it in GitHub Desktop.
Path matching in TypeScript to allow type-safe extraction of path params as union type
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
// ID for the parameter | |
type ParamId<T> = T; | |
type ParamKey<Component> = Component extends `:${infer NameWithPattern}` | |
? `param_${ParamId<NameWithPattern>}` | |
: never; | |
type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}` | |
? ParamKey<Component> | ParamKeys<Rest> | |
: ParamKey<Path>; | |
type Keys = ParamKeys<"/:a/user/:b/:c">; | |
// This is a really cool trick: | |
// 1. Recursive tyepes | |
// 2. Template literal types to extract the components from the provided path. | |
// 3. Note that this only works at compile time using compile-time constants. Otherwise the whole thing falls apart. | |
// If you don't have compile-time constants, things could still fail at runtime. | |
const x: Keys = "param_a"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment