Web Analytics

Intersection Types

Intermediate~18 min

Intersection types combine multiple types into one using AND logic. The result must have ALL properties from all types.

TypeScript Intersection Types

Basic Intersection Types

Output
Click Run to execute your code
Intersection Syntax: Use the ampersand & to combine types: type C = A & B

When to Use Intersection Types

  • Mixins: Combine multiple behaviors
  • Composition: Build complex types from simple ones
  • Extending types: Add properties to existing types
  • Multiple constraints: Require all properties

Intersection vs Union

Feature Intersection (&) Union (|)
Logic AND - must have ALL OR - can be ANY
Properties Combined from all types Only common properties
Use case Composition, mixins Flexible parameters
Example A & B has all from A and B A | B is either A or B

Common Mistakes

1. Conflicting Property Types

type A = { value: string };
type B = { value: number };

type C = A & B;  // value is never (impossible!)

// ✓ Better - compatible types
type A = { name: string };
type B = { age: number };
type C = A & B;  // { name: string; age: number }

2. Confusing & with |

// ✗ Wrong - using union when intersection needed
function merge(a: Named | Aged) {
    // Can't access both name and age
}

// ✓ Correct - intersection requires both
function merge(a: Named & Aged) {
    console.log(a.name, a.age);  // ✓ OK
}
Best Practice: Use intersection types for composition. They're perfect for combining multiple interfaces or type aliases.

Summary

  • Intersection types use & for AND logic
  • Result must have ALL properties from all types
  • Perfect for composition and mixins
  • Avoid conflicting property types