What if your code could instantly know exactly what kind of data it's dealing with, avoiding costly mistakes?
Why Discriminated unions in Typescript? - Purpose & Use Cases
Imagine you have different types of shapes like circles and squares, and you want to write code that handles each shape differently. Without a clear way to tell which shape you have, you might write many if-else checks scattered everywhere.
This manual approach is slow and confusing. You might forget a case, mix up properties, or write repetitive code. It's easy to make mistakes and hard to maintain as your program grows.
Discriminated unions let you tag each shape with a unique label. This way, TypeScript knows exactly which shape you have and what properties it has. Your code becomes cleaner, safer, and easier to understand.
if (shape.type === 'circle') { // handle circle } else if (shape.type === 'square') { // handle square }
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; size: number };
function area(shape: Shape) {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.size ** 2;
}
}It enables writing clear, error-free code that safely handles different data types with confidence.
Think of a messaging app where messages can be text, images, or videos. Discriminated unions help you handle each message type correctly without confusion.
Manual type checks are error-prone and messy.
Discriminated unions tag data with unique labels for clarity.
This leads to safer, cleaner, and easier-to-maintain code.