AI Hints
Home›TypeScript Tutorial›Types from Types
TypeScript · Lesson 68 of 120

Conditional Types

If for types.

⏱ 2 min read▶ Video at 52:02🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

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.

Conditional Types
From the video: Conditional Types
  • 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.

keyvalue
Union ineach member checked
null→ never
nevervanishes
Built inNonNullable<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