# Discriminated Unions — TypeScript

Source: https://www.geekswithgeeks.com/en/typescript/ts-discriminated-unions

> A shared literal field lets TS narrow a union exhaustively.

## A discriminated union

Give every variant a shared literal field (`kind`) — TS uses it to know exactly which shape you're holding.

```typescript
interface Circle {
  kind: "circle";
  radius: number;
}
interface Square {
  kind: "square";
  side: number;
}
type Shape = Circle | Square;
```

## Exhaustive switch

Switching on `kind` narrows each case automatically, with no manual casting.

```typescript
function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
  }
}
```

## Exhaustiveness checking

Add a `default: const _exhaustive: never = shape;` branch — if a new shape variant is ever added and not handled, TS flags it at compile time.
