0
0
Typescriptprogramming~5 mins

Why union types are needed in Typescript

Choose your learning style9 modes available
Introduction

Union types let you say a value can be one of several types. This helps your program accept different kinds of data safely.

When a function can accept more than one type of input, like a number or a string.
When a variable might hold different types at different times, like a string or null.
When you want to allow multiple possible types for a property in an object.
When handling user input that could be a number or text.
When working with APIs that return different types depending on the situation.
Syntax
Typescript
let variable: type1 | type2 | type3;

The pipe symbol | means "or" between types.

You can combine as many types as you need using |.

Examples
This variable can hold either a string or a number.
Typescript
let value: string | number;
value = "hello";
value = 42;
The function accepts an ID that can be a number or a string.
Typescript
function printId(id: number | string) {
  console.log(`ID: ${id}`);
}
printId(101);
printId("202");
This type only allows specific string values.
Typescript
type Status = "success" | "error" | "loading";
let currentStatus: Status = "loading";
Sample Program

This program shows how union types let a function handle both strings and numbers safely by checking the type first.

Typescript
function formatInput(input: string | number) {
  if (typeof input === "string") {
    return `Text: ${input.toUpperCase()}`;
  } else {
    return `Number: ${input.toFixed(2)}`;
  }
}

console.log(formatInput("hello"));
console.log(formatInput(3.14159));
OutputSuccess
Important Notes

Use union types to make your code flexible but still safe.

Always check the type before using methods specific to one type.

Summary

Union types let variables hold multiple types.

They help functions accept different kinds of inputs.

They improve code safety by forcing type checks.