0
0
Typescriptprogramming~3 mins

Why Type alias for unions in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could fix all your type checks in one place instead of hunting them down everywhere?

The Scenario

Imagine you are writing a program that accepts different types of inputs, like numbers or strings, and you have to check each type everywhere in your code manually.

The Problem

Manually checking and writing the same union of types repeatedly makes your code long, confusing, and easy to make mistakes. If you want to change the types later, you have to find and update every place.

The Solution

Using a type alias for unions lets you name a group of types once and reuse it everywhere. This keeps your code clean, easy to read, and simple to update.

Before vs After
Before
function process(input: number | string | boolean) { /* ... */ }
function validate(value: number | string | boolean) { /* ... */ }
After
type Input = number | string | boolean;
function process(input: Input) { /* ... */ }
function validate(value: Input) { /* ... */ }
What It Enables

You can write clearer, shorter code that is easier to maintain and update when your types change.

Real Life Example

Think of a form that accepts user input as text or numbers. Using a type alias for the allowed input types makes handling the form data simpler and less error-prone.

Key Takeaways

Type aliases let you name complex unions once.

This reduces repetition and mistakes in your code.

It makes updating types easier and your code cleaner.