Route parameter extraction
Concept and syntax
A conditional template can extract a single trailing named route parameter and use it as a key. This deliberately limited grammar accepts a static prefix followed by /:name. Multiple parameters, optional segments, escaping and URL decoding require a real parser and broader type design.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Params<R>=R extends `${string}/:${infer K}`?Record<K,string>:Record<string,never>;const p:Params<"/orders/:id">={id:"42"}; console.log(p.id);Expected output:
42Common mistake
Intentionally invalid; compile separately and do not execute.
type Params<R>=R extends `${string}/:${infer K}`?Record<K,string>:Record<string,never>;const p:Params<"/orders/:id">={name:"42"};Expected diagnostic: TS2353. The extracted key is id, not name.
Practice and recap
Design a two-segment grammar separately before adding recursion.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Route parameter extraction — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Route parameter extraction is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Params<R>=R extends `${string}/:${infer K}`?Record<K,string>:Record<string,never>;const p:Params<"/orders/:id">={id:"42"}; console.log(p.id);Which diagnostic and explanation match the rejected example under the lesson settings?
type Params<R>=R extends `${string}/:${infer K}`?Record<K,string>:Record<string,never>;const p:Params<"/orders/:id">={name:"42"};Which property is required by Params<"/orders/:orderId">?