TypeScript · Lesson 68 of 120
Conditional Types
If for types.
A conditional type chooses between two types, like an if statement. It's written with extends, a question mark, and a colon, just like the ternary operator.

- If for types
- extends ? :
- Like a ternary
Choosing a type
Is text checks whether T extends string. If so, the type is yes, otherwise no. Then, a more useful one. Non null removes null and undefined from a union. Run it.
app.tstypescript
type IsText<T> = T extends string ? "yes" : "no";
const a: IsText<"Leeds"> = "yes";
const b: IsText<42> = "no";
type NonNull<T> = T extends null | undefined ? never : T;
type Coupon = NonNull<string | null | undefined>; // string
const c: Coupon = "SAVE10";
console.log(a, b, c);Output
yes no SAVE10
Distributing over unions
When T is a union, a conditional type is applied to each member separately. That's why non null works. Null and undefined become never, and never disappears from a union.
| key | value |
|---|---|
| Union in | each member checked |
| null | → never |
| never | vanishes |
| Built in | NonNullable<T> |
Summary
Conditional types pick a type with extends, question mark, and colon. Next, infer.
Key takeaways- T extends U ? X : Y
- Per union member
- NonNullable
Next up: infer — pull a type out