Last active
October 31, 2022 08:06
-
-
Save FredricW/ecba07f8082804f025f87327c2dcab8f to your computer and use it in GitHub Desktop.
Parse url path into Typescript types
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
/** | |
* 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