Combination with union
- TypeScript course
- Advanced
- Lesson 6/57
- 4 min
Learn to produce string sets with unions.
Combination with union
When a union is placed inside a template literal type, TypeScript generates all combinations. This works like a cartesian product. Each union member is placed into the template separately and the result is again a union.
type Ans = "yes" | "no";
type Sentence = `Result: ${Ans}`;
// "Result: yes" | "Result: no"Cartesian product with two unions
If you put two unions in the same template, all combinations of each are generated. For example, color and size unions combined in a `${Renk}_${Boyut}` template make each color pair with each size. This is a practical way to generate names with fixed options.
type Color = "red" | "blue";
type Size = "S" | "M";
type Product = `${Color}_${Size}`;
// 4 combinationsPractice Color and Size combination
Define a union named Renk: "kırmızı" | "mavi". Define a union named Boyut: "S" | "M". Define a template literal type named Urun: `${Renk}_${Boyut}`. The urun variable should be of type Urun with value "kırmızı_S". Print urun with console.log.
Starter code
// Renk adinda union tanimla
// Boyut adinda union tanimla
// Urun adinda template literal ile kombinasyon turu tanimla
// urun degiskenini tanimla ve deger ata
// urun yazdirSample solution
type Renk = "kırmızı" | "mavi";
type Boyut = "S" | "M";
type Urun = `${Renk}_${Boyut}`;
const urun: Urun = "kırmızı_S";
console.log(urun);Expected output
kırmızı_S
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If type Yan = "evet" | "hayır" and type Cumle = `Sonuç: ${Yan}`, what is Cumle?
- "Sonuç: evet" | "Sonuç: hayır" Correct answer
- "Sonuç: evet"
- ("Sonuç: evet" | "Sonuç: hayır")[]
- string
Explanation: When a union is placed inside a template literal, a separate literal is produced for each member; the result is the union of all those literals.
2 Union operator
type Yan = "evet" ____ "hayır";
type Cumle = `Sonuç: ${Yan}`;
type Yan = "evet" | "hayır";
type Cumle = `Sonuç: ${Yan}`;
Explanation: You separate union type members with the | operator; each member is a separate option.
3 Union combination concepts
| Term | Meaning |
|---|---|
| |
Union operator |
cartesian product |
All combinations |
${Yan} |
Union placed in template |
"evet" | "hayır" |
Two-member union |