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

TypeScript 中Omit 工具類型的實用技巧

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

前言

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

什么是 Omit?

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

基本語法

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

簡單示例

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

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

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

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

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

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

Omit 的實用技巧

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

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

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

// 創(chuàng)建文章時,不需要提交 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;
}

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

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

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

3. 確保屬性名準確無誤

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

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

// 嘗試 Omit 一個不存在的屬性 'descripton' (拼寫錯誤)
// type ProductSummary = Omit<Product, 'descripton' | 'sku'>;
// TypeScript 編譯器會報錯:
// 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)建一個可修改部分配置的類型,但不允許修改 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'>;
// 或者更簡潔地,如果目標是讓部分屬性可選,同時排除其他屬性:
type ModifiableConfig = Omit<Partial<Config>, 'id'>;
// ModifiableConfig = { apiKey?: string; timeout?: number; debugMode?: boolean; }
// 注意:這種組合方式需要仔細考慮最終生成的類型結(jié)構(gòu)是否符合預(yù)期。

// 一個更常見的組合:創(chuàng)建一個類型,其中某些屬性被省略,其余屬性變?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 中一對功能相對的工具類型:

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

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

選擇使用哪個取決于你的意圖:

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

總結(jié)

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

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

相關(guān)文章

最新評論

施秉县| 武川县| 沅江市| 江陵县| 黑龙江省| 合肥市| 井研县| 湘潭县| 平阴县| 新河县| 永平县| 霍邱县| 高唐县| 静安区| 甘洛县| 新余市| 灵寿县| 纳雍县| 门头沟区| 昭觉县| 丁青县| 吴江市| 淮北市| 太康县| 安西县| 苏尼特左旗| 南充市| 济阳县| 佳木斯市| 云安县| 瓮安县| 济宁市| 凭祥市| 大邑县| 钟祥市| 贵港市| 合江县| 政和县| 阜宁县| 吉隆县| 仪征市|