0
0
Typescriptprogramming~5 mins

Union type syntax and behavior 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 inputs safely.

When a function can accept either a string or a number as input.
When a variable might hold a value that can be a boolean or a string.
When you want to allow multiple types for a parameter but still keep type safety.
When reading data that might come in different formats, like a string or an array.
Syntax
Typescript
let variableName: Type1 | Type2 | Type3;

The vertical bar | means "or" between types.

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

Examples
This means value can be a string or a number.
Typescript
let value: string | number;
This function accepts an id that can be a number or a string.
Typescript
function printId(id: number | string) {
  console.log(`ID: ${id}`);
}
This variable can only be one of these three string values.
Typescript
let status: 'success' | 'error' | 'loading';
Sample Program

This program shows how to handle a value that can be a string or a number. It checks the type and uses the right method.

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

console.log(formatInput('hello'));
console.log(formatInput(42));
OutputSuccess
Important Notes

When using union types, you often need to check the type before using type-specific methods.

TypeScript helps catch errors if you try to use a method that doesn't exist on all types in the union.

Summary

Union types let variables hold values of different types safely.

Use the | symbol to separate types in a union.

Always check the type before using type-specific features.