Try   HackMD

typescript: Extract

Extract 工具型別

前言

在使用 enum 或是一些限縮條件下的型別時,往往不知道如何描述其型別。 extract 提供了一個方便的方式來讓 typescript 知道我們想要的型別限縮範圍**

涵義解釋:

Extract 是 TypeScript 的一個條件型別,它用於從一個較大的型別(通常是聯合型別)中選出符合「特定」條件的型別。

舉個例:

type PrimitiveTypes = string | number | boolean;
type OnlyString = Extract<PrimitiveTypes, string>;

假設我們有一個聯合型別 PrimitiveTypes,包含 stringnumberboolean 這三種基本型別。
當我們使用 Extract<PrimitiveTypes, string> 時,我們就是在問:“在 PrimitiveTypes 中,有哪些型別是 string 型別?”
所以只有 string 會成立。
因此,OnlyString 的型別會是 string

好處:

這種方式的好處在於它提供了一種靈活而強大的方式來選擇型別。這在處理複雜的型別系統時特別有用,比如當你有一個包含多種型別的聯合型別,並且你只想處理其中的某些特定型別時。

常見用法與範例:

  1. 過濾特定型別的元素:

    ​​​type Event = 'click' | 'scroll' | 'mousemove' | number;
    ​​​type StringEvent = Extract<Event, string>;
    ​​​// StringEvent 型別是 'click' | 'scroll' | 'mousemove'
    

    Event 聯合型別中提取了所有的 string 型別成員。

  2. 從枚舉中提取特定的值:

    ​​​enum Status { New = 'new', InProgress = 'inProgress', Completed = 'completed' }
    ​​​type ActiveStatus = Extract<Status, 'new' | 'inProgress'>;
    ​​​// ActiveStatus 的型別是 'new' | 'inProgress'
    

Status 枚舉中提取了符合 'new' 或 'inProgress' 的成員。

  1. 函數參數的限制:

    ​​​type Pets = 'dog' | 'cat' | 'bird';
    ​​​type DomesticPets = 'dog' | 'cat';
    
    ​​​function adoptPet(pet: Extract<Pets, DomesticPets>) {
    ​​​    // ...
    ​​​}
    ​​​
    ​​​adoptPet('dog'); // 正確
    ​​​adoptPet('bird'); // 錯誤,因為 'bird' 不在 'dog' | 'cat' 的範圍內
    

    adoptPet 的參數 pet 被限制為只能是 Pets 中也屬於 DomesticPets 的型別。