Advertisement
Advanced TypeScript, Template Literal Types

How would you use 'infer' inside a template literal type's conditional check to parse and extract a portion of a string literal type?

Short answer

Combine a conditional type with a template literal PATTERN on the 'extends' side, using 'infer' at the specific position you want to capture — TypeScript pattern-matches the string literal against the template shape and extracts the inferred substring as its own type.

Save TypeScript mock interview
Advertisement
AModel answer
Combine a conditional type with a template literal PATTERN on the 'extends' side, using 'infer' at the specific position you want to capture — TypeScript pattern-matches the string literal against the template shape and extracts the inferred substring as its own type.
type ExtractRouteParam<T extends string> =
  T extends `${string}:${infer Param}` ? Param : never;
type Param1 = ExtractRouteParam<'/users/:id'>; // 'id'
type Param2 = ExtractRouteParam<'/posts/:postId'>; // 'postId'
Real-world example
Building a fully type-safe router library that extracts route parameter names directly from a route path's literal string type.
Likely follow-ups
  • How would you extend this to extract MULTIPLE route parameters from a path with several ':param' segments?
Related topics