What is a conditional type?
- TypeScript course
- Intermediate
- Lesson 36/89
- 4 min
Learn conditional types that branch by type.
What is a conditional type?
A conditional type is a type expression that branches based on a type. In T extends U ? X : Y, if T is assignable to U the type becomes X; otherwise Y. It resembles JavaScript's ternary operator but works at the type level and is evaluated at compile time.
type Etiket<T> =
T extends string ? "metin" : "sayi";
type A = Etiket<string>; // "metin"
type B = Etiket<number>; // "sayi"Compile-time evaluation
Conditional types are evaluated at compile time and leave no runtime trace. Since the result is a type, it can only appear in type positions (variable declarations, parameters, returns). It cannot be used as a value; a call like console.log(Etiket<number>) is invalid.
Practice Label type
Write the conditional type Etiket<T> as T extends string ? "metin" : "sayi". Define variable a with type Etiket<string> and assign "metin". Define variable b with type Etiket<number> and assign "sayi". Print both with console.log on separate lines.
Starter code
// Etiket<T> koşullu türünü tanımla
// T string ise "metin", değilse "sayi"
// a değişkenini Etiket<string> türünde tanımla, "metin" ata
// b değişkenini Etiket<number> türünde tanımla, "sayi" ata
// her ikisini ayrı satırlarda yazdırSample solution
type Etiket<T> = T extends string ? "metin" : "sayi";
const a: Etiket<string> = "metin";
const b: Etiket<number> = "sayi";
console.log(a);
console.log(b);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<number> become below?
type Etiket<T> = T extends string ? "metin" : "sayi";
type R = Etiket<number>;- never
- "metin"
- "sayi" Correct answer
- number
Explanation: Since number is not assignable to string, the condition is false and the result is the "sayi" literal type. "metin" is the true branch; number and never are wrong inferences.
2 Add the condition
type Etiket<T> =
T ____ string ? "metin" : "sayi";
type Etiket<T> =
T extends string ? "metin" : "sayi";
Explanation: To query in a conditional type you use extends. implements is for classes; instanceof checks values; is is not a keyword here in TypeScript.
3 Conditional type parts
| Term | Meaning |
|---|---|
T extends U |
The condition |
? X |
Type when true |
: Y |
Type when false |
Etiket<string> |
Usage example |