最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

TypeScript 中Omit 工具類型的實(shí)用技巧

 更新時(shí)間:2026年05月13日 09:39:20   作者:哈希茶館  
Omit是TypeScript中一個(gè)工具類型,用于從現(xiàn)有類型中排除特定屬性,創(chuàng)建新類型,本文介紹了Omit的基本用法、實(shí)用技巧、與Partial、Readonly等等結(jié)合使用,感興趣的可以了解一下

前言

在 TypeScript 開發(fā)中,我們經(jīng)常需要基于現(xiàn)有類型創(chuàng)建新的類型。有時(shí),我們希望新類型繼承原類型的大部分屬性,但排除掉其中一小部分。Omit<Type, Keys> 工具類型正是為此而生,它提供了一種簡(jiǎn)潔、類型安全的方式來(lái)實(shí)現(xiàn)這一需求。本文將帶你了解 Omit 的基本用法和一些實(shí)用技巧。

什么是 Omit?

Omit<Type, Keys> 是 TypeScript 內(nèi)置的一個(gè)工具類型,它的作用是構(gòu)造一個(gè)新類型,該類型擁有 Type 的所有屬性,但排除了 Keys 中指定的屬性。這里的 Keys 通常是一個(gè)字符串字面量,或者是字符串字面量的聯(lián)合類型。

基本語(yǔ)法

type NewType = Omit<OriginalType, 'propToExclude1' | 'propToExclude2'>;

簡(jiǎn)單示例

假設(shè)我們有一個(gè) User 接口:

interface User {
  id: number;
  name: string;
  email: string;
  isAdmin: boolean;
  createdAt: Date;
}

如果我們想創(chuàng)建一個(gè)不包含 emailisAdmin 屬性的 UserProfile 類型,可以這樣做:

type UserProfile = Omit<User, 'email' | 'isAdmin'>;

// 此時(shí),UserProfile 類型等同于:
// {
//   id: number;
//   name: string;
//   createdAt: Date;
// }

const userProfile: UserProfile = {
  id: 1,
  name: 'Alice',
  createdAt: new Date(),
};
// userProfile.email; // 類型錯(cuò)誤:屬性“email”在類型“UserProfile”上不存在。

Omit 的實(shí)用技巧

1. 創(chuàng)建用于數(shù)據(jù)提交的類型

在創(chuàng)建或更新實(shí)體時(shí),某些字段(如 idcreatedAt、updatedAt 等)通常是由后端生成或管理的,前端提交數(shù)據(jù)時(shí)不需要包含它們。Omit 可以幫助我們方便地從完整的實(shí)體類型中派生出用于提交的載荷(Payload)類型。

interface Article {
  id: string;
  title: string;
  content: string;
  authorId: number;
  views: number;
  createdAt: Date;
  updatedAt: Date;
}

// 創(chuàng)建文章時(shí),不需要提交 id, views, createdAt, updatedAt
type CreateArticlePayload = Omit<Article, 'id' | 'views' | 'createdAt' | 'updatedAt'>;

// CreateArticlePayload 類型為:
// {
//   title: string;
//   content: string;
//   authorId: number;
// }

function submitNewArticle(payload: CreateArticlePayload) {
  // ...提交邏輯
  console.log(payload.title);
}

submitNewArticle({
  title: 'Understanding Omit in TypeScript',
  content: 'Omit is a powerful utility type...',
  authorId: 101,
});

2. 隱藏敏感或不必要的信息

interface UserAccount {
  userId: string;
  username: string;
  email: string;
  passwordHash: string; // 敏感信息
  internalFlags: string; // 內(nèi)部信息
  isActive: boolean;
}

// 定義一個(gè)公開的用戶信息類型,不包含 passwordHash 和 internalFlags
type PublicUserInfo = Omit<UserAccount, 'passwordHash' | 'internalFlags'>;

// PublicUserInfo 類型為:
// {
//   userId: string;
//   username: string;
//   email: string;
//   isActive: boolean;
// }

function getUserInfoForClient(account: UserAccount): PublicUserInfo {
  // 實(shí)際實(shí)現(xiàn)中,你可能需要手動(dòng)挑選屬性或使用庫(kù)
  // 但類型定義確保了返回對(duì)象的結(jié)構(gòu)是正確的
  return {
    userId: account.userId,
    username: account.username,
    email: account.email,
    isActive: account.isActive,
  };
}

3. 確保屬性名準(zhǔn)確無(wú)誤

Omit 的第二個(gè)參數(shù) Keys 必須是 keyof Type 的子集。這意味著如果你嘗試排除一個(gè)在原始類型中不存在的屬性名,TypeScript 編譯器會(huì)報(bào)錯(cuò)。這有助于在編譯階段就發(fā)現(xiàn)屬性名的拼寫錯(cuò)誤。

interface Product {
  sku: string;
  name: string;
  price: number;
  description: string;
}

// 嘗試 Omit 一個(gè)不存在的屬性 'descripton' (拼寫錯(cuò)誤)
// type ProductSummary = Omit<Product, 'descripton' | 'sku'>;
// TypeScript 編譯器會(huì)報(bào)錯(cuò):
// Type '"descripton"' does not satisfy the constraint 'keyof Product'.

// 正確的寫法
type ProductSummary = Omit<Product, 'description' | 'sku'>;
// ProductSummary 類型為:
// {
//   name: string;
//   price: number;
// }

4. 與其他工具類型結(jié)合

Omit 可以與其他 TypeScript 工具類型(如 Partial, Readonly)結(jié)合使用,創(chuàng)建更復(fù)雜的類型轉(zhuǎn)換。

interface Config {
  readonly id: string;
  apiKey: string;
  timeout: number;
  debugMode: boolean;
}

// 假設(shè)我們想創(chuàng)建一個(gè)可修改部分配置的類型,但不允許修改 id,并且 debugMode 是可選的
// 1. 先 Omit掉 id
type ConfigWithoutId = Omit<Config, 'id'>;
// ConfigWithoutId = { apiKey: string; timeout: number; debugMode: boolean; }

// 2. 再將 debugMode 設(shè)為可選
type UpdateConfigPayload = Partial<Pick<ConfigWithoutId, 'debugMode'>> & Omit<ConfigWithoutId, 'debugMode'>;
// 或者更簡(jiǎn)潔地,如果目標(biāo)是讓部分屬性可選,同時(shí)排除其他屬性:
type ModifiableConfig = Omit<Partial<Config>, 'id'>;
// ModifiableConfig = { apiKey?: string; timeout?: number; debugMode?: boolean; }
// 注意:這種組合方式需要仔細(xì)考慮最終生成的類型結(jié)構(gòu)是否符合預(yù)期。

// 一個(gè)更常見的組合:創(chuàng)建一個(gè)類型,其中某些屬性被省略,其余屬性變?yōu)榭蛇x
type OptionalEditableUser = Partial<Omit<User, 'id' | 'createdAt'>>;
// OptionalEditableUser 類型為:
// {
//   name?: string;
//   email?: string;
//   isAdmin?: boolean;
// }

Omit vs. Pick

Omit<T, K>Pick<T, K> 是 TypeScript 中一對(duì)功能相對(duì)的工具類型:

  • Pick<T, K>: 從類型 T選取 一組屬性 K 來(lái)構(gòu)造一個(gè)新類型。
  • Omit<T, K>: 從類型 T排除 一組屬性 K 來(lái)構(gòu)造一個(gè)新類型。

實(shí)際上,Omit<T, K> 在內(nèi)部可以理解為 Pick<T, Exclude<keyof T, K>>。

選擇使用哪個(gè)取決于你的意圖:

  • 當(dāng)你明確知道想要 保留 哪些少數(shù)屬性時(shí),使用 Pick 更直觀。
  • 當(dāng)你明確知道想要 移除 哪些少數(shù)屬性時(shí),使用 Omit 更方便。

總結(jié)

Omit 是 TypeScript 工具類型庫(kù)中一個(gè)非常實(shí)用且強(qiáng)大的成員。它通過(guò)允許我們從現(xiàn)有類型中排除特定屬性,簡(jiǎn)化了創(chuàng)建新類型定義的過(guò)程,從而提高了代碼的類型安全性、可讀性和可維護(hù)性。熟練掌握 Omit 的使用,能讓你的 TypeScript 代碼更加靈活和健壯。

到此這篇關(guān)于TypeScript 中Omit 工具類型的實(shí)用技巧的文章就介紹到這了,更多相關(guān)TypeScript Omit工具類型內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

鄯善县| 西城区| 托克托县| 从江县| 九江县| 保亭| 海南省| 洞口县| 拉萨市| 文昌市| 响水县| 巴彦淖尔市| 新乐市| 海原县| 洛阳市| 太谷县| 仁布县| 甘泉县| 忻州市| 开平市| 鹤岗市| 工布江达县| 定南县| 湟源县| 高州市| 墨竹工卡县| 荥阳市| 卓尼县| 和田县| 巴里| 丰顺县| 嘉荫县| 五河县| 修水县| 霍城县| 紫云| 南部县| 永川市| 盈江县| 开化县| 贺兰县|