You're required to implement a type-level parser to parse URL params string into an Union. Learn conditional types with `infer` in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a type-level parser that extracts URL parameter names (prefixed with :) from a URL path string and produces a union of those parameter names.
You're required to implement a type-level parser to parse URL params string into an Union.
ParseUrlParams<':id'> // id
ParseUrlParams<'posts/:id'> // id
ParseUrlParams<'posts/:id/:user'> // id | userChange the following code to make the test cases pass (no type check errors).
type cases = [
Expect<Equal<ParseUrlParams<''>, never>>,
Expect<Equal<ParseUrlParams<':id'>, 'id'>>,
Expect<Equal<ParseUrlParams<'posts/:id'>, 'id'>>,
Expect<Equal<ParseUrlParams<'posts/:id/'>, 'id'>>,
Expect<Equal<ParseUrlParams<'posts/:id/:user'>, 'id' | 'user'>>,
Expect<Equal<ParseUrlParams<'posts/:id/:user/like'>, 'id' | 'user'>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type ParseUrlParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? Param | ParseUrlParams<Rest>
: T extends `${string}:${infer Param}`
? Param
: neverHow it works:
:param followed by a / and more content. If so, it extracts the parameter name Param and recursively processes the Rest of the string.:param appears at the end of the string with no trailing /. It extracts just that final parameter name.: parameter segments remain), it returns never, which is the identity element for union types.${string} prefix in each template literal pattern matches any leading characters before the :, allowing parameters to appear anywhere in the path.This challenge helps you understand recursive template literal type parsing with infer and how to apply this concept in real-world scenarios like type-safe routing.
This challenge is originally from here.