# 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](../narrowing) 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](../narrowing)
{% endtab %}
{% endtabs %}
