0Pricing
TypeScript Academy · Lesson

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

  1. Mapped types with +/-readonly and +/-?
  2. Key remapping & template literal types
  3. String-pattern typing (route params, event names)
← Back to TypeScript Academy