Lesson 4 of 56 · Typescript
Union & Intersection Types
Duration: 20 minutes
Union Types (|)
A value can be one of several types.
type Status = "success" | "error" | "pending";
let s: Status = "success"; // OK
s = "loading"; // ❌ Not assignable
Intersection Types (&)
A value must satisfy all constituent types.
interface A { a: string; }
interface B { b: number; }
type AB = A & B; // must have both a and b
const obj: AB = { a: "foo", b: 123 };
Practical example – API response
type Success = { ok: true; data: string; };
type Failure = { ok: false; error: string; };
type ApiResult = Success | Failure;
function handle(r: ApiResult) {
if (r.ok) {
console.log(r.data); // `data` is guaranteed here
} else {
console.error(r.error);
}
}