Tagged Union Types

aushwin

RetrO_o

Posted on October 13, 2022

Tagged Union Types

Union types with a common tag. And whats special with these tags is that they help in discriminating the types which are combines to make the union type.

For example lets create three shapes circle, rectangle, triangle .

interface Circle {
    type: 'circle';
    radius: number;
}

interface Rectangle {
    type: 'rectangle';
    height: number;
    width: number;
}

interface Triangle {
    type: 'triangle';
    height: number;
    width: number;
}
Enter fullscreen mode Exit fullscreen mode

Now lets create a union type with it

type Shapes = Circle | Rectangle | Triangle
Enter fullscreen mode Exit fullscreen mode

The benefit of having a property which is discriminating from all interfaces is that it helps in narrowing down the type while using it.

Practically, let's define a function which returns area of the Shapes passed in

const area = (shapes: Shapes) {

}
Enter fullscreen mode Exit fullscreen mode

Now if you accessing shapes , it won't provide all properties in each interfaces rather it would provide the property which is common in all interfaces .

Which is actually a good thing because we can use this to narrow down our types . Which essentially means the discriminated property acts as a type guard .So now lets narrow down our types using a switch statement

Since we are discriminating using the common property within the interfaces, now typescript can easily differentiate interfaces within the union type .

πŸ’– πŸ’ͺ πŸ™… 🚩
aushwin
RetrO_o

Posted on October 13, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related