Extract
是 TypeScript 中內置的工具類型,它用于從聯合類型中提取出符合某個條件的類型,生成一個新的類型。這個工具類型在日常開發中非常有用,它能夠幫助我們編寫類型安全的代碼和更好地實現代碼復用。
/** * Extract from T those types that are assignable to U. * typescript/lib/lib.es5.d.ts */type Extract<T, U> = T extends U ? T : never;type T0 = Extract<"a" | "b" | "c", "a" | "f">// type T0 = "a"
本文我將介紹 Extract
工具類型的 8 個使用技巧,掌握這些技巧之后,在工作中你就能更好地利用 Extract
type MyTypes = string | number | boolean;type StringOrNumber = Extract<MyTypes, string | number>;let uid: StringOrNumber = "semlinker" // Okuid = 2024 // Okuid = false // Error// Type 'boolean' is not assignable to type 'StringOrNumber'.
type Color = 'red' | 'green' | 'blue' | 'yellow';type PrimaryColors = Extract<Color, 'red' | 'green' | 'blue'>;const primaryColor: PrimaryColors = 'blue'; // Okconst secondaryColor: PrimaryColors = 'yellow'; // Error// Type '"yellow"' is not assignable to type 'PrimaryColors'.
type Value = string | number | (() => void);type CallableFn = Extract<Value, Function>;const fn1: CallableFn = () => console.log('semlinker'); // Okconst fn2: CallableFn = 'semlinker'; // Error// Type 'string' is not assignable to type '() => void'.
type TaskStatus = "Todo" | "InProgress" | "Done" | "Archived";type ModuleHandledStatus = "Todo" | "Done" | "OnHold";type ModuleSpecificStatus = Extract<TaskStatus, ModuleHandledStatus>;// type ModuleSpecificStatus = "Todo" | "Done"
Animal 聯合類型,包含了多種動物的描述對象,我們想從中提取出含有 "legs" 屬性的子類型。
type Animal = | { type: 'dog', legs: number } | { type: 'cat', legs: number } | { type: 'fish', fins: number };type AnimalsWithLegs = Extract<Animal, { legs: number }>;const dog: AnimalsWithLegs = { type: 'dog', legs: 4 }; // Okconst cat: AnimalsWithLegs = { type: 'cat', legs: 4 }; // Okconst fish: AnimalsWithLegs = { type: 'fish', fins: 6 }; // Error// Type '"fish"' is not assignable to type '"dog" | "cat"'.
type EventTypes = MouseEvent | KeyboardEvent | TouchEvent;type OnlyMouseEvents = Extract<EventTypes, MouseEvent>;function handleMouseEvent(event: OnlyMouseEvents) { console.log('Handling mouse event:', event.clientX, event.clientY);}document.addEventListener('click', (event) => { handleMouseEvent(event); // OK});document.addEventListener('keydown', (event) => { handleMouseEvent(event); // Error // Argument of type 'KeyboardEvent' is not assignable to parameter of type 'MouseEvent'.});
使用 Extract 可以在類型守衛中精確地過濾類型,使得在條件分支中可以安全地使用過濾后的類型。
type Pet = { type: 'dog', bark: () => void } | { type: 'cat', meow: () => void };function isDog(pet: Pet): pet is Extract<Pet, { type: 'dog' }> { return pet.type === 'dog';}const pet1: Pet = { type: 'dog', bark: () => console.log('Woof!') }const pet2: Pet = { type: "cat", meow: () => console.log("Meow!") }console.log(`pet1 is dog: ${isDog(pet1)}`) // "pet1 is dog: true" console.log(`pet2 is dog: ${isDog(pet2)}`) // "pet2 is dog: false"
在處理 API 請求的場景中,我們需要根據不同的請求類型(如 GET、POST、DELETE)處理不同類型的數據。為了增強類型安全和確保每種請求類型都正確地處理其數據,我們可以利用 TypeScript 的函數重載和 Extract 工具類型。
type RequestType = 'GET' | 'POST' | 'DELETE';type RequestData = { GET: undefined; POST: { body: string }; DELETE: { resourceId: number };};// Function overloading, based on the request type, accepts matching data typesfunction sendRequest<T extends RequestType>(type: 'GET', data: Extract<RequestData[T], undefined>): void;function sendRequest<T extends RequestType>(type: 'POST', data: Extract<RequestData[T], { body: string }>): void;function sendRequest<T extends RequestType>(type: 'DELETE', data: Extract<RequestData[T], { resourceId: number }>): void;function sendRequest<T extends RequestType>(type: T, data: RequestData[T]): void { console.log(`Sending ${type} request with data:`, data);}sendRequest('GET', undefined); // OksendRequest('POST', { body: "semlinker" }); // OksendRequest('DELETE', { resourceId: 2024 }); // OksendRequest('POST', { body: 2024 }); // Error// Type 'number' is not assignable to type 'string'.sendRequest('DELETE', undefined); // Error// Argument of type 'undefined' is not assignable to parameter of type '{ resourceId: number; }'.
本文鏈接:http://www.www897cc.com/showinfo-26-78509-0.htmlExtract 工具類型八個使用技巧
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com