What if you could write one function that safely handles many types without messy code?
Why union types are needed in Typescript - The Real Reasons
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.
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.
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.
function process(input: string) { /* handle string only */ }
function processNumber(input: number) { /* handle number only */ }function process(input: string | number) { /* handle string or number */ }Union types enable flexible and safe code that can work with different kinds of data without extra complexity.
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.
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.