What if you could tell your program to accept different kinds of data without messy checks everywhere?
Why Union type syntax and behavior in Typescript? - Purpose & Use Cases
Imagine you are writing a program that accepts user input which could be either a number or a string. Without union types, you have to write separate code blocks to handle each type manually, checking and converting types everywhere.
This manual checking is slow and error-prone. You might forget a check, causing bugs or crashes. The code becomes long and hard to read, making it difficult to maintain or update.
Union types let you declare a variable that can hold multiple types in a clean way. The TypeScript compiler helps you by checking your code and guiding you to handle each type properly, reducing errors and making your code simpler.
function process(input: any) {
if (typeof input === 'string') {
// handle string
} else if (typeof input === 'number') {
// handle number
}
}function process(input: string | number) {
if (typeof input === 'string') {
// handle string
} else {
// handle number
}
}It enables writing safer and clearer code that naturally handles multiple types without extra boilerplate.
For example, a function that accepts either a user ID as a number or a username as a string can be typed with a union, making the code easier to understand and less buggy.
Manual type checks are slow and error-prone.
Union types let variables hold multiple types cleanly.
They help write safer, clearer, and easier-to-maintain code.