A Mini Type-Level Route Parser
Parse route paths into typed parameter objects.
The Goal
We build a route parser that reads a path like "users/:id/posts/:postId" and produces a typed params object { id: string; postId: string }, entirely at compile time. This is a real pattern used by typed routers.
type Params = ParseRoute<"users/:id/posts/:postId">;
// Goal: { id: string; postId: string }Recognizing a Parameter
A path segment is a parameter when it starts with ":". We match that prefix with a template literal and infer the parameter name after the colon.
Notation: real TypeScript writes template literal types with backtick-delimited strings containing dollar-brace holes. In these snippets we show that pattern as Tpl<...>, listing each part in order; e.g. a backtick template matching the literal prefix then Rest appears as Tpl<'prefix', infer Rest>.
type ParamName<S> = S extends Tpl<':', infer Name> ? Name : never;
// Tpl<...> denotes a backtick template literal type: a colon then Name
type X = ParamName<':id'>; // 'id'
type Y = ParamName<'users'>; // neverAll lessons in this course
- Parser Combinator Concepts
- Type-Level String Splitting
- Parsing with Template Literals
- A Mini Type-Level Route Parser