Summary - Template literal types
- TypeScript course
- Advanced
- Lesson 8/57
- 4 min
Write a CSS class name generator with template literals.
Summary - Template literal types
In this group you learned template literal types: backtick and ${} create type-level template strings; unions produce a cartesian product; mapped types produce a template literal value or key for each key. Together you can type-safely define names with fixed options such as CSS class names.
type Color = "red" | "blue";
type Mode = "light" | "dark";
type Class = `btn-${Mode}-${Color}`;Practice Write a CSS class generator
Define a union named Mod: "acik" | "koyu". Define a union named Renk: "kirmizi" | "mavi". Define a template literal type named Sinif: `btn-${Mod}-${Renk}`. The sinif variable should be of type Sinif with value "btn-acik-kirmizi". Print sinif with console.log.
Starter code
// Mod adinda union tanimla
// Renk adinda union tanimla
// Sinif adinda template literal tur tanimla
// sinif degiskenini tanimla ve deger ata
// sinif yazdirSample solution
type Mod = "acik" | "koyu";
type Renk = "kirmizi" | "mavi";
type Sinif = `btn-${Mod}-${Renk}`;
const sinif: Sinif = "btn-acik-kirmizi";
console.log(sinif);Expected output
btn-acik-kirmizi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the best way to define CSS class names type-safely?
- Leaving it to any
- Using the number type
- Using template literal type and union Correct answer
- Using the plain string type
Explanation: Template literal type and union together produce types that accept only valid combinations of fixed options; this is the most type-safe way.
2 Template with two unions
type Mod = "acik" | "koyu";
type Renk = "kirmizi" | "mavi";
type Sinif = `btn-${____}-${Renk}`;
type Mod = "acik" | "koyu";
type Renk = "kirmizi" | "mavi";
type Sinif = `btn-${Mod}-${Renk}`;
Explanation: The first union placed in the template is Mod; this produces combinations like `btn-light-red`.
3 Template literal summary
| Term | Meaning |
|---|---|
`...${T}...` |
Template string type |
union |
Produces combinations |
mapped |
Per-key value |
cartesian product |
All pairs |