Skip to content

Instantly share code, notes, and snippets.

@FredricW
Last active October 31, 2022 08:06
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 FredricW/ecba07f8082804f025f87327c2dcab8f to your computer and use it in GitHub Desktop.
Save FredricW/ecba07f8082804f025f87327c2dcab8f to your computer and use it in GitHub Desktop.
Parse url path into Typescript types
/**
* Extracts url wildcards formatted as a string beginning with colon.
* ```
* 'user/:userId/profile' -> 'userId'
* ```
*
* Multiple instances yields a union type:
* ```
* 'user/:userId/contacts/:listId' -> 'userId' | 'listId'
* ```
*/
type GetColonKeysFromUrlPath<T> = T extends `${string}:${infer InitialKey}`
? InitialKey extends `${infer Key}/${infer Rest}`
? Key | GetColonKeysFromUrlPath<Rest>
: InitialKey
: never;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment