> ## Documentation Index
> Fetch the complete documentation index at: https://docs.baenninger.me/llms.txt
> Use this file to discover all available pages before exploring further.

# Union Types

Union Types stellen Werte dar, die einen von mehreren Typen darstellen können.

```typescript theme={null}
const printId = (id: number | string) => {
  console.log(`ID: ${id}`);
}
```

Der senkrechte Strich kann als "oder" gelesen werden. Dies ist nützlich, wenn du mehrere Typen akzeptieren willst.

***

Du kannst auch einen benannten Union-Typ deklarieren.

```typescript theme={null}
type Id = number | string;
```

Diesen kannst du dann wie einen normalen Type verwenden.

```typescript theme={null}
const printId = (id: Id) => {
  console.log(`ID: ${id}`);
}
```

***

Union Types sind auch bei literalen Typen oft nützlich.

```typescript theme={null}
type Direction = "left" | "right" | "up" | "down";

const move = (direction: Direction) => {
  console.log(`Moving ${direction}`);
}
```

***

Mit Union Types können wir auch Objekte verwenden.

```typescript theme={null}
type Vehicle = { hasWheels: boolean } | { canFly: boolean };

const car: Vehicle = { hasWheels: true };
const airplane: Vehicle = { canFly: true };
const flyingCar: Vehicle = { hasWheels: true, canFly: true };
flyingCar.hasWheels = true;
```
