Intersection Types

1. Welcome and Icebreaker:

  • If you could combine two superpowers, which would you choose and why?

2. Outline the Session:

  • We’ll learn about intersection types in TypeScript: how to combine multiple types into one.
  • Learning Outcomes: Understand how to use & to create types that have all properties of multiple types.
  • Let’s see how to build more complex types!

3. Concept Explanation:

  • Intersection Types use the & operator to combine two or more types into one. The resulting type has all the properties of the combined types.
  • Syntax:
    type A = { a: number };
    type B = { b: string };
    type C = A & B; // { a: number; b: string }
    
  • Useful for combining different interfaces or type aliases, especially when you want an object to satisfy multiple contracts.
  • If there are overlapping properties, their types must be compatible.

4. Live Coding Demonstration:

type Person = {
  name: string;
  age: number;
};

type Employee = {
  employeeId: number;
  department: string;
};

type EmployeeProfile = Person & Employee;

const profile: EmployeeProfile = {
  name: "Alice",
  age: 30,
  employeeId: 101,
  department: "Engineering"
};
console.log(profile);

// Intersection with interfaces
interface A {
  a: number;
}
interface B {
  b: string;
}
const ab: A & B = { a: 1, b: "test" };
console.log(ab);

// Overlapping properties (must be compatible)
type X = { value: number };
type Y = { value: number; label: string };
type XY = X & Y; // { value: number; label: string }
const xy: XY = { value: 5, label: "five" };
console.log(xy);

5. Tasks:

  • Short Exercise:
    1. Define two types: Contact (with email and phone) and Address (with street, city).
    2. Create a new type ContactInfo as the intersection of Contact and Address.
    3. Create a variable of type ContactInfo and initialize it with appropriate values.
    4. Print all properties of your ContactInfo object.