JS Guide
HomeQuestionsSearchResources
Search

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
PrevNext
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 types
// 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

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?