CodeBlanks Logo Icon CodeBlanks

Distributive conditional

Learn distribution and unions.

Distributive conditional

When a conditional type is used on a union type, distribution occurs. Etiket<string | number> is evaluated separately for each member: Etiket<string> | Etiket<number>. The result is the union of each branch.

type Etiket<T> =
  T extends string ? "metin" : "sayi";
type R = Etiket<string | number>;
// "metin" | "sayi"

The basis of distribution

Distribution happens automatically when the type parameter on the left of a conditional is a union. The condition is evaluated separately for each member and the results combine. This is the core mechanism for filtering specific types from a union (Exclude, Extract).

Practice Label a union

Write the conditional type Etiket<T> as T extends string ? "metin" : "sayi". Define type Sonuclar as Etiket<string | number>. Define variable dizi with type Sonuclar[] and assign ["metin", "sayi"]. Print dizi[0] and dizi[1] on separate lines.

Starter code

index.ts
// Etiket<T> koşullu türünü tanımla
// T string ise "metin", değilse "sayi"
// Sonuclar türünü Etiket<string | number> olarak tanımla
// dizi değişkenini Sonuclar[] türünde tanımla, ["metin", "sayi"] ata
// dizi[0] ve dizi[1]'i ayrı satırlarda yazdır

Sample solution

index.ts
type Etiket<T> = T extends string ? "metin" : "sayi";
type Sonuclar = Etiket<string | number>;
const dizi: Sonuclar[] = ["metin", "sayi"];
console.log(dizi[0]);
console.log(dizi[1]);

Expected output

metin
sayi

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does Etiket<string | number> produce with a distributive conditional?

index.ts
type Etiket<T> = T extends string ? "metin" : "sayi";
type R = Etiket<string | number>;
  • string | number
  • never
  • "metin"
  • "metin" | "sayi" Correct answer

Explanation: Distribution evaluates each member separately: "metin" for string, "sayi" for number. The result is the union of these literal types. string | number or never is wrong; just "metin" is incomplete.

2 Distribution with a union

Question
type Etiket<T> = T extends string ? "metin" : "sayi";
type R = Etiket<____>;
// R: "metin" | "sayi"
Answer
type Etiket<T> = T extends string ? "metin" : "sayi";
type R = Etiket<string | number>;
// R: "metin" | "sayi"

Explanation: For distribution to produce a union, the type parameter must be a union. Bare string gives one branch; bare number gives one branch; string & number reduces to never.

3 Distributive conditional parts

Term Meaning
Etiket<string | number> Distributive call
Etiket<string> First member evaluation
Etiket<number> Second member evaluation
"metin" | "sayi" Distribution result

All lessons in Intermediate