# Union Type

> A type for a value that can be one of a few kinds. It may be text or a number.

**Field:** Software Development  
**Category:** Programming Paradigms  
**Also known as:** Union Types, Sum Type, Either Type

## Think of it like

It is like a box marked toys or books. You know it holds one of the two, and nothing else.

## Definition

A union type says a value can be one of a few types. In TypeScript, string | number means a string or a number. The type checker then makes you handle each case before you use the value. Unions are also how many languages say a value may be missing, like string | null. Rust and Swift build the same idea into enums.

## Example

An id field can hold 42 or "A-42". Lucy types it as number | string, and the checker makes her handle both.

## Example code

```typescript
function show(id: number | string) {
  if (typeof id === "number") return id.toFixed(0);
  return id.toUpperCase();
}
```

The value is a number or a string. Each branch handles one case.

## Why it matters

Real data often comes in more than one shape. A union names every shape, so none is forgotten.

## Common mistake

Using a union, then treating the value as one type only. The checker stops that, so handle each case.

## Three principles

- **One of a few.** The value is this type or that one.
- **Check, then use.** Each case is handled on its own.
- **Missing values.** Often written as a type or null.

## Related terms

- [Type System](https://learn.benibix.com/term/development/type-system)
- [Data Type](https://learn.benibix.com/term/development/data-type)
- [Null Safety](https://learn.benibix.com/term/development/null-safety)
- [Enumeration (Enum)](https://learn.benibix.com/term/development/enum)
- [TypeScript](https://learn.benibix.com/term/development/typescript)
- [Generics](https://learn.benibix.com/term/development/generics)

## Told apart from

- [Generics vs Union Type](https://learn.benibix.com/compare/generics-vs-union-type): People think generics and union types both just mean any type. A union type lists a few kinds a value may be, such as a string or a number, and you must check which one you have. A generic stands for one type that the caller picks. That type is then kept exact all the way through, so a list of strings gives back a string.

![Three panels. Struct: one box named Point holding x and y together. Union type: a value that is either a string or a number, shown as two doors with or between them. Composition: a Car box that holds an Engine box and four Wheel boxes inside it.](https://learn.benibix.com/diagrams/dev7-data-shapes.svg)

---

Source: https://learn.benibix.com/term/development/union-type
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
