MediumConcept

What are union and intersection types in TypeScript?

Technology:
TypeScript
Experience:
Junior,
Mid-level

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.

Detailed explanation

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.

  • TypeScriptEasy

    What is TypeScript and why do we use it?

    TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It catches type errors in the editor and at build time, and it documents the shape of data for the next person who reads the code.

    Intern · Junior · Types & Type System
  • TypeScriptMedium

    What are generics in TypeScript?

    Generics are type parameters: they let a function, class or type work with many types while keeping the relationship between inputs and outputs, instead of falling back to any.

    Junior · Mid-level · Types & Type System
  • TypeScriptMedium

    What are utility types in TypeScript like Partial, Pick and Omit?

    Utility types are built-in helpers that transform an existing type: Partial makes every field optional, Required the opposite, Pick keeps a set of keys, Omit removes them, and Record builds a key/value map.

    Junior · Mid-level · Types & Type System
  • TypeScriptMedium

    What is type narrowing in TypeScript?

    Narrowing is when TypeScript shrinks a wide type (such as a union) to a more specific type after a runtime check like typeof, instanceof, in, or a custom type guard.

    Mid-level · Senior · Types & Type System