0
0
Typescriptprogramming~3 mins

Why union types are needed in Typescript - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if you could write one function that safely handles many types without messy code?

The Scenario

Imagine you are building a form where a user can enter either a phone number or an email address. Without union types, you have to create separate variables or functions for each input type, making your code bulky and confusing.

The Problem

Manually handling multiple possible types means writing repetitive checks and separate code paths. This slows you down and increases the chance of mistakes, like forgetting to handle one type or mixing up data.

The Solution

Union types let you declare a variable or function parameter that can accept multiple types in a clean, simple way. This means you write less code and handle all cases clearly and safely.

Before vs After
Before
function process(input: string) { /* handle string only */ }
function processNumber(input: number) { /* handle number only */ }
After
function process(input: string | number) { /* handle string or number */ }
What It Enables

Union types enable flexible and safe code that can work with different kinds of data without extra complexity.

Real Life Example

When building a chat app, a message might be text or an image URL. Using union types, you can handle both message types in one function easily.

Key Takeaways

Manual handling of multiple types is repetitive and error-prone.

Union types let you combine multiple types in one place.

This leads to cleaner, safer, and more flexible code.