0
0
Typescriptprogramming~5 mins

Type alias for unions in Typescript

Choose your learning style9 modes available
Introduction

A type alias for unions lets you give a name to a group of types. This makes your code easier to read and reuse.

When you want to allow a variable to hold one of several types.
When you want to simplify complex type definitions by naming them.
When you want to reuse the same union type in many places.
When you want to make your code clearer by giving meaningful names to type groups.
Syntax
Typescript
type AliasName = Type1 | Type2 | Type3;

The type keyword creates a new name for a type.

The vertical bar | means "or" between types.

Examples
This means ID can be a number or a string.
Typescript
type ID = number | string;
This means Status can be one of three specific words.
Typescript
type Status = 'success' | 'error' | 'loading';
This means Result can be true, false, or no value.
Typescript
type Result = boolean | null | undefined;
Sample Program

This program defines a type alias Pet for three pet names. The function greetPet accepts only these names and prints a greeting.

Typescript
type Pet = 'dog' | 'cat' | 'fish';

function greetPet(pet: Pet) {
  console.log(`Hello, dear ${pet}!`);
}

greetPet('dog');
greetPet('cat');
OutputSuccess
Important Notes

Type aliases do not create new types, they just name existing ones.

Union types let you accept multiple types but still keep type safety.

Summary

Type alias for unions gives a name to multiple possible types.

Use type Alias = Type1 | Type2; to create one.

This helps make code clearer and easier to maintain.