Template literal unions
Concept and syntax
A template literal type combines literal alternatives in its placeholders. Each finite union contributes a cross product of possible strings. Unlike a runtime template expression, the type describes permitted strings without constructing any value.
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 Topic=`${"read"|"write"}:${"file"|"cache"}`;const x:Topic="read:cache"; console.log(x);Expected output:
read:cacheCommon mistake
Intentionally invalid; compile separately and do not execute.
type Topic=`${"read"|"write"}:${"file"|"cache"}`;const x:Topic="read:queue";Expected diagnostic: TS2322. queue is not a resource in the second placeholder.
Practice and recap
Enumerate all four allowed topics.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Template literal unions — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Template literal unions is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Topic=`${"read"|"write"}:${"file"|"cache"}`;const x:Topic="read:cache"; console.log(x);Which diagnostic and explanation match the rejected example under the lesson settings?
type Topic=`${"read"|"write"}:${"file"|"cache"}`;const x:Topic="read:queue";How many different values does Topic allow?