TypeScript中使用Omit來排除 interface property | TypeScript
在使用TypeScript開發應用程式時,我們常常需要定義新的 Interface 來描述物件的形狀和結構。有時候,我們可能需要在一個介面中排除某些屬性,而不是直接複製所有屬性到一個新的 Interface。這時,TypeScript提供了一個非常方便的工具:
Omit。
Omit 是 TypeScript 中的一個內置的工具類型(utility type),它可以用來從一個 Interface 中排除指定的屬性,然後返回一個新的介面。讓我們通過一個簡單的例子來看看如何使用 Omit。
假設我們有一個產品介面 ProductInfo,它描述了一個商品的屬性:
export interface ProductInfo {
id: number;
title: string;
slug: string;
unit_price: number;
discount: number;
inventory: number;
thumb: string;
is_deleted: boolean;
}
現在,假設我們想要創建一個新的介面 ProductInfoSerialized,它基於 ProductInfo,但排除了 unit_price 和 is_deleted 屬性,同時將它們分別更名為 unitPrice 和 isDeleted。我們可以使用 Omit 來實現這一目標:
interface ProductInfoSerialized extends Omit<ProductInfo, "unit_price" | "is_deleted"> {
unitPrice: number;
isDeleted: boolean;
}
在這個例子中,我們使用 Omit<ProductInfo, 'unit_price' | 'is_deleted'> 來排除了 unit_price 和 is_deleted 屬性,然後再加上 unitPrice 和 isDeleted 屬性,得到了我們想要的 ProductInfoSerialized 介面。
使用 Omit 可以幫助我們保持介面的清晰和簡潔,同時提高了代碼的可讀性和可維護性。這是 TypeScript 中一個非常實用的工具,特別是在處理大型專案時。我們可以在不影響舊有的程式碼情形下去進行修改。
Tags