Summary - Conditional types
- TypeScript course
- Intermediate
- Lesson 39/89
- 4 min
Write a type filter with conditional types.
Summary - Conditional types
Conditional types are type expressions that branch based on a type. With T extends U ? X : Y for branching, distribution for union filtering, and never for removing members, you can write type filters. Exclude and Extract are built this way.
type MetinAl<T> =
T extends string ? T : never;
type R = MetinAl<"a" | 1 | "b">;
// "a" | "b"Practice Type filter
Write the conditional type MetinAl<T> as T extends string ? T : never. Define type Metinler as MetinAl<"elma" | 42 | "armut">. Define variable dizi with type Metinler[] and assign ["elma", "armut"]. Print dizi[0] and dizi[1] on separate lines.
Starter code
// MetinAl<T> koşullu türünü tanımla
// T string ise T, değilse never
// Metinler türünü MetinAl<"elma" | 42 | "armut"> olarak tanımla
// dizi değişkenini Metinler[] türünde tanımla, ["elma", "armut"] ata
// dizi[0] ve dizi[1]'i ayrı satırlarda yazdırSample solution
type MetinAl<T> = T extends string ? T : never;
type Metinler = MetinAl<"elma" | 42 | "armut">;
const dizi: Metinler[] = ["elma", "armut"];
console.log(dizi[0]);
console.log(dizi[1]);Expected output
elma armut
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which conditional type keeps only string members from a union?
type MetinAl<T> = T extends string ? T : never;
type R = MetinAl<"a" | 1 | "b">;- T extends string ? T : never Correct answer
- T extends number ? T : never
- T extends string ? never : T
- T extends string ? string : number
Explanation: T extends string ? T : never keeps string members as-is and makes the rest never. The first removes strings; the second changes the type; the last keeps numbers.
2 Type filter body
type MetinAl<T> =
T extends string ? ____ : never;
type R = MetinAl<"a" | 1 | "b">;
// R: "a" | "b"
type MetinAl<T> =
T extends string ? T : never;
type R = MetinAl<"a" | 1 | "b">;
// R: "a" | "b"
Explanation: To keep string members with their literal types, the true branch must be T. never removes all; string loses the literal types; any breaks type safety.
3 Match conditional type logic
| Term | Meaning |
|---|---|
T extends U ? X : Y |
Basic conditional type |
T extends string ? T : never |
Keeps string members |
Dağıtıcı koşullu |
Evaluates union members one by one |
MetinAl<"a" | 1> |
Example of a filtered type |