0
0
Typescriptprogramming~3 mins

Why Union type syntax and behavior in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could tell your program to accept different kinds of data without messy checks everywhere?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
function process(input: any) {
  if (typeof input === 'string') {
    // handle string
  } else if (typeof input === 'number') {
    // handle number
  }
}
After
function process(input: string | number) {
  if (typeof input === 'string') {
    // handle string
  } else {
    // handle number
  }
}
What It Enables

It enables writing safer and clearer code that naturally handles multiple types without extra boilerplate.

Real Life Example

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.

Key Takeaways

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.