TypeScript Tutorial

Union & Intersection Types

Combining types with | and & for complex data modeling

What are Union Types (|)?

In TypeScript, a Union Type is a way to tell the compiler that a variable can be one of several different types. This is incredibly powerful for handling data that might change, like an ID that could be a string OR a number.
typescript
// ID can be string OR number!
const userId: string | number = 10;

// userId = true; // ERROR: true is NOT string or number!

What are Intersection Types (&)?

An Intersection Type allows you to combine multiple types into ONE final type. The resulting object must have all the properties of every type in the intersection. This is a common, flexible alternative to using interface extends.
typescript
type Name = { name: string };
type Age = { age: number };

// Must have BOTH!
type Person = Name & Age;

const me: Person = { 
    name: "Alpha", 
    age: 25 
};

Comparisons: Union (|) vs. Intersection (&)

Wait! How do you remember which one is which?
| Feature | Union (|) | Intersection (&) | | :--- | :--- | :--- | | Logic | "OR": One of these. | "AND": ALL of these. | | Common Use | API status codes, IDs, colors. | Merging small, reusable types. |

Practical Example: Discriminated Unions

This is the most powerful use of unions. You distinguish between several "objects" by looking at a shared "type" property.
typescript
interface Success {
  type: "success";
  data: string;
}

interface Failure {
  type: "error";
  message: string;
}

type Response = Success | Failure;

function handle(resp: Response) {
  if (resp.type === "success") {
    // TS knows this is a Success object!
    console.log(resp.data);
  }
}

Summary

TypeSyntaxPurpose
Union`stringnumber`
Literal Union`"dark""light"`
IntersectionTypeA & TypeBMust satisfy ALL types
Best ForFlexible APIs, complex state, merging data
SafetyTS ensures you handle each case! (See Type Guards!)
MixedCombine multiple unions/intersections!
RefactorConvert separate variables into one clean union!
ModernThe hallmark of a modern, flexible TS project
InterfaceUse interface extends for object hierarchies
AliasUse type aliases (type X = ...) for unions
NarrowTS "narrows" the type as your code gets specific!
EqualityUse === to distinguish between union members!
Nullable`stringnull` (A value that can be missing!)
Optionalprop?: string is secretly `stringundefined`!
LogicThe power of modeling data with "sum" and "product" types
SecurityPrevents accessing properties that aren't common to all union types
StandardEstablished and trusted worldwide for 10+ years
ExhaustiveTS can check if you've handled ALL cases of a union (See Switch!)
ToolingPerfect autocomplete in VS Code for literal values!
CleanYour code reads like logical documentation
GenericUnions and Intersections can also be generic!
OverlapBe careful with overlapping property names in intersections!