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 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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount