Template infer patterns
Concept and syntax
An infer placeholder in a conditional template matches a segment of a string literal. The false branch handles strings that do not fit. A broad string cannot be assumed to match a required prefix.
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 Resource<T>=T extends `api/${infer R}`?R:never;const x:Resource<"api/users">="users"; console.log(x);Expected output:
usersCommon mistake
Intentionally invalid; compile separately and do not execute.
type Resource<T>=T extends `api/${infer R}`?R:never;const x:Resource<"web/users">="users";Expected diagnostic: TS2322. The prefix does not match, yielding never.
Practice and recap
Extract a prefix and suffix separated by a colon.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Template infer patterns — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Template infer patterns is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Resource<T>=T extends `api/${infer R}`?R:never;const x:Resource<"api/users">="users"; console.log(x);Which diagnostic and explanation match the rejected example under the lesson settings?
type Resource<T>=T extends `api/${infer R}`?R:never;const x:Resource<"web/users">="users";What does Resource<"api/orders"> evaluate to?