String-pattern typing (route params, event names)
Constrain strings with template literal types: route parameter patterns, event name namespaces, and safe builders.
Intro
Goal: Model string formats in types. With template literal types you can enforce patterns like "/users/:id" or "user:created" while keeping great DX.
- Constrain by prefix/suffix
- Extract pieces with
infer - Build safe helpers
Route params
A simple route template and infer the parameter name; never in cases that do not comply with the rule.
type Route = `/${string}`
type RouteWithParam = `/${string}/:${string}`
type ParamOf<R extends string> = R extends `${string}/:${infer P}` ? P : never
// examples
type A = ParamOf<"/users/:id"> // "id"
type B = ParamOf<"/posts/:slug"> // "slug"All lessons in this course
- Mapped types with +/-readonly and +/-?
- Key remapping & template literal types
- String-pattern typing (route params, event names)