Junior (0-2 years)TypeScript

What are union and intersection types in TypeScript?

Quick answer

A union (A | B) is a value that is one of the members. An intersection (A & B) is a value that must satisfy both types at once.

Unions model “this or that”: a result that is { ok: true, data: T } | { ok: false, error: string }. Narrow with a discriminant field (ok) before you read data. Intersections model “this and that”: User & { role: "admin" } has every User field plus role.

A union of objects is not an object with optional fields. A | B only lets you access properties common to both until you narrow. That is the usual bug when someone writes user.role on a User | Admin without checking.