> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/appendix/typescript/type/union/discriminated-union.md).

# discriminated union

{% hint style="info" %}
When **every type** in a **union** contains a **common property** with **literal types**, TypeScript considers that to be a ***discriminated union***, and can [narrow out](/web/appendix/typescript/type/narrowing.md) the members of the union.
{% endhint %}

{% tabs %}
{% tab title="discriminated union" %}

```typescript
interface Circle {
  kind: "circle";      // common property with literal types
  radius: number;
}
 
interface Square {
  kind: "square";      // common property with literal types
  sideLength: number;
}

// ⭐️ `kind` is considered a discriminant property of `Shape`
type Shape = Circle | Square;

// switch on shape.kind
function getArea(shape: Shape) {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.radius ** 2; 
    case "square": return shape.sideLength ** 2;
  }
}
```

{% endtab %}

{% tab title="📗 參考" %}

* 📘 [Discriminated Union](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions)
* 📘 [Exhaustiveness checking](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#exhaustiveness-checking) (the [`never`](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-never-type) type) ⭐️
  {% endtab %}

{% tab title="👉 相關" %}

* [Narrowing](/web/appendix/typescript/type/narrowing.md)
  {% endtab %}
  {% endtabs %}
