TypeScript-Exclude

Exclude<UnionType, ExcludedMembers>

顧名思義,就是排除某些類型的意思。
引用官方的說法:從 UnionType 中排除所有可分配給 ExcludedMembers 的聯合成員,以構建一個新的類型。

Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers

用法

1.排除某個型別

type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"

2.排除多個型別

type text = "A" | "B" | "C" | "D" | "E";
type T1 = Exclude<text, "A" | "B" | "C">; // "D" | "E"

3.排除某個類型

type T2 = Exclude<number | "b" | "c", string>; // number

4.排除物件類型

type animal = &#123;name: "dog"&#125; | &#123;name: "cat"&#125; | &#123;name: "pig"&#125;;
type T3 = Exclude<animal, &#123;name: "dog"&#125;>; // &#123;name:"cat"&#125; | &#123;name:"pig"&#125;

5.藉由形狀排除型別

type animal = &#123;name: "dog"; age: number&#125; | &#123;name: "cat"&#125; | &#123;name: "pig"&#125;;
type T4 = Exclude<animal, &#123;age: number&#125;>; // &#123;name:"cat"&#125; | &#123;name:"pig"&#125;

6.藉由樣板文字排除型別

type animal = "Adog" | "Bcat" | "Cdog" | "Dpig";
type T5 = Exclude<animal, `$&#123;string&#125;$&#123;"dog" | "cat"&#125;`>; //"Dpig"

小結

Exclude 用來排除某些型別,可以用來排除單一型別、多個型別、某個類型、物件類型、形狀、樣板文字等等。

參考資料

Exclude
9 Ways to Use Exclude in TypeScript-Matt Pocock

相關文章

TypeScript-常用功能-Readonly
TypeScript

2024/01/31

TypeScript 的 LeetCode-TypeHero
TypeScript TypeHero

2024/01/26

TypeScript-介面(interface) vs 型別別名(Aliases)
TypeScript

2024/01/19