TypeScript tutorial: Lesson 20 – Intersection Types


Intersection types are closely related to union types, but they are used very differently. An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the features you need. For example, Animal & hasEgg & BirdData is a type which is all of Animal and hasEgg and BirdData. That means an object of this type will have all members of all three types.

Example:

interface Animal {
    name: string
}

interface hasEgg {
    layEggs(): void
}

interface BirdData {
    fly(): void    
}

interface FishData {
    swim(): void
}

type IBird = Animal & hasEgg & BirdData
type IFish = Animal & hasEgg & FishData

class Bird implements IBird{
    name: string = ""
    fly():void {

    }
    layEggs():void {

    }
}

class Fish implements IFish{
    name: string = ""
    swim():void {

    }
    layEggs():void {

    }
}

Leave a Reply