If we want to get the most out of Typescript Types, we need to ensure that we are specific in how we define them. A loosely defined type might be better than not having them, but their impact will not be as good as having Types that properly reflect our data.
Let’s take the simplest example I can think of - Shapes. In shapes, we can have Circles, Rectangles, Squares, etc., you get the idea. There is no way you can have a single type alias that can cover all shapes without compromising on something.
If we were to define a Shape
type alias for just the above three shapes, it would need to account for the possibility that all fields are not there for all shapes, i.e., Circle only has a radius, which doesn’t exist in either Rectangle or Square, while the circle doesn’t have either width or height. As you can imagine, our problem only becomes more extensive as you add more shapes.
So, our type alias would look like this.
type Shape = {
radius?: Number; // For Circle
length?: Number; // For Rectangle
width?: Number; // For Rectangle
side?: Number; // For Square side Length
}
From the above example, the type alias above is not very useful since if you had a circle, you could easily leave out all fields or add all of them to Shape
and typescript will not be able to help you at all; all it can do is offer autocompletion hints for you.
And discriminated unions come to the rescue.