JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
PrevNext

Learn the concept

Union & Intersection Types

typescript
junior
unions

What are union and intersection types in TypeScript?

unions
intersections
type-narrowing
discriminated-unions
Quick Answer

Union types (A | B) represent values that can be one of several types - use when a value could be different types. Intersection types (A & B) combine multiple types into one - use when a value must satisfy all types simultaneously.

Detailed Explanation

Union Types (|):

  • Value can be ANY ONE of the types
  • "Either this OR that"
  • Narrow with type guards before accessing specific properties
  • Common for function parameters that accept multiple types

Intersection Types (&):

  • Value must satisfy ALL types
  • "This AND that"
  • Combines properties from multiple types
  • Used for mixing object types

Type Narrowing:

  • Process of refining union types
  • Use typeof, instanceof, or custom type guards
  • TypeScript tracks narrowed type in branches

Code Examples

Union typesTypeScript
// Union of primitives
type ID = string | number;

function printId(id: ID) {
  // Can only access properties common to both types
  console.log(id.toString()); // OK - both have toString()
  
  // Must narrow before type-specific operations
  if (typeof id === 'string') {
    console.log(id.toUpperCase()); // OK - narrowed to string
  } else {
    console.log(id.toFixed(2)); // OK - narrowed to number
  }
}

printId(123);     // OK
printId('abc');   // OK
printId(true);    // Error: boolean not assignable to ID

// Union of literal types (string literals)
type Direction = 'north' | 'south' | 'east' | 'west';

function move(direction: Direction) {
  console.log(`Moving ${direction}`);
}

move('north'); // OK
move('up');    // Error: 'up' is not assignable to Direction

Real-World Applications

Use Cases

State Machine Modeling

Using discriminated unions to represent application states (loading, success, error) with type-safe transitions

API Response Handling

Modeling success/error responses as discriminated unions for exhaustive error handling

Form Field Variants

Typing different form field types (text, select, checkbox) as a discriminated union with field-specific props

Mini Projects

Traffic Light State Machine

beginner

Model traffic light states as a discriminated union with type-safe transition functions

Type-Safe Result Monad

intermediate

Implement a Result<T, E> type using discriminated unions with map, flatMap, and match operations

Industry Examples

Redux Toolkit

Uses discriminated union action types for type-safe reducer pattern matching

tRPC

Uses discriminated unions for type-safe API response handling

Resources

TypeScript - Union Types

docs

TypeScript - Narrowing

docs

Related Questions

What are type guards in TypeScript and how do you create custom ones?

mid
type-guards

What are generics in TypeScript and how do you use them?

mid
generics
Previous
What is the difference between interfaces and type aliases in TypeScript?
Next
How do you type functions in TypeScript?
PrevNext