Skip to content

Instantly share code, notes, and snippets.

@a10y
Created September 29, 2023 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a10y/ac9404dcd67933b94b819be2de2f6c63 to your computer and use it in GitHub Desktop.
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
// 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