Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SViccari/9b4872618995d80de00af4e1c617c7ac to your computer and use it in GitHub Desktop.
Save SViccari/9b4872618995d80de00af4e1c617c7ac to your computer and use it in GitHub Desktop.
Intersections and Unions and Discriminated Unions, Oh My!

Intersection Type

An Intersection Type takes two objects and creates a new object that combines the features of both objects.

Below is an example where we create an Intersection Type (ShapeProps) which combines all the properties defined for Square, Rectangle and Circle.

interface Square {
    kind: "square";
    size: number;
}
interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}
interface Circle {
    kind: "circle";
    radius: number;
}

type ShapeProps = Square & Rectangle & Circle;

function area(s: ShapeProps): string {
  /** Combines all of the shape properties and exposes them as properties on ShapeProps */
  return `${s.kind}, ${s.size}, ${s.width}, ${s.height}, ${s.radius}`
}

Discriminated Union

Unions are used to specify a value that can be one of several types. Discriminated Unions help distinguish between the several tyoes.

For example, given an object with a literal member (ex: kind: "rectangle"), this property can be used to distinguish between other objects with the same literal member (ex: kind: "square").

This allows us to specify that Shape is either a Square or a Rectangle and then use the tag or discriminant (in this case, the kind property) to determine if Shape is a Square or Rectangle.

interface Square {
    kind: "square";
    size: number;
}

interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}

type Shape = Square | Rectangle;

function area(s: Shape) {
    switch (s.kind) {
        case "square": return s.size * s.size;
        case "rectangle": return s.height * s.width;
    }
}

Recap Intersection vs Discriminated Union - why does it matter?

The Discriminated Union specifies that the Shape is either a Square or a Rectangle, while an Intersection specifies that Shape is an object that combines the properties of Square and Rectangle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment