TS常用內置工具類Omit、Pick、Partial、Required、Readonly、Exclude 、Extract、ReturnType、NonNullable - 2024-05-17

TS中常用的工具映射類型,讓寫TS時效率大大提升,避免無意義的重復性定義。

1.Omit 省略/剔除

顧名思義 可以剔除 已定義對象中 自己不需要的一部分形成新的定義類型。

interface UserObj {
    readonly name: string; // readonly 只讀屬性 只能初始化定義 不能二次賦值
    age: number;
    id: number;
    sex: 0 | 1;
    address: string;
    weight: number;
}

// 剔除省略自己不需要的
type Person = Omit<UserObj, "age" | "sex"  | "address" | "weight">;

// 此時Person 等同于 Person1

interface Person1 {
    readonly name: string;
    id: number;
}
// Omit 的源碼
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

2.Pick 采集

顧名思義,可以采集 已定義對象中 自己需要的一部分形成新的定義類型。

interface UserObj {
    readonly name: string;
    age: number;
    id: number;
    sex: 0 | 1;
    address: string;
    weight: number;
 }
 
 // 采集需要的
 type Person = Pick<UserObj, "name" | "id">;
 
 // 此時Person 等同于 Person1
 interface Person1 {
     readonly name: string;
     id: number;
}
// Pick 的源碼
type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};

3.Partial

可把定義好的對象(包含 必選+可選項)類型全部轉化為可選項

// 已有定義類型Person
interface Person {
    name: string;
    age: number;
    id: number;
    sex: 0 | 1;
    address: string;
    weight: number;
}

// 使用方法
const newObj: Partial<Person> = {
    name: '張三' // 假如只需要一項 Partial的便捷性 可以不需要從新定義類型
};

// Partial<Person>等同于 NewPerson
interface NewPerson {
    name?: string;
    age?: number;
    id?: number;
    sex?: 0 | 1;
    address?: string;
    weight?: number;
}

Partial的源碼,非常簡單,自己就可以實現(xiàn)一個簡易版

type Partial<T> = {
    [P in keyof T]?: T[P];
};

4.Required (必選的)

Required 和 Partial剛好相反,可把定義好的對象(包含 必選+可選項)類型全部轉化為 必選項

// 已有定義類型Person
interface Person {
    name: string;
    age: number;
    id?: number;
    sex?: 0 | 1;
}

// 使用方法
const newObj: Required<Person> = {
    name: '張三',
    age: 1,
    id: 1,
    sex: 1
};

// Required<Person>等同于 NewPerson
interface NewPerson {
    name: string;
    age: number;
    id: number;
    sex: 0 | 1;
}
Required的源碼實現(xiàn)也非常簡單,"-?" 意思是移除可選屬性
/**
 * Make all properties in T required
 */
type Required<T> = {
    [P in keyof T]-?: T[P];
};

5.Readonly (轉化只讀)

Readonly 就是為類型對象每一項添加前綴 Readonly

interface Person {
    readonly name: string; // 只有這一項有readonly
    age: number;
    id?: number;
}

// 使用方法
const newObj: Readonly<Person> = {
    name: '張三',
    age: 1,
    id: 1
};
// newObj.name = '李四'; // 異常 因為有readonly只讀屬性,只能初始化聲明,不能賦值。

// Readonly<Person> 等同于 NewPerson
interface NewPerson {
    readonly name: string;
    readonly age: number;
    readonly id?: number;
}
Readonly的源碼實現(xiàn)也非常簡單
/**
 * Make all properties in T readonly
 */
type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

6.Extract (提取/包括)

一般用于處理聯(lián)合類型

// Extract實現(xiàn)源碼 原理很簡單
type Extract<T, U> = T extends U ? T : never;
// 處理聯(lián)合類型
type Test1 = '1' | '2' | '3'

const obj: Extract<Test1, '1' | '2'> = '1'; // 1,2 OK 賦值3就會error

7.Exclude (排除/不包括)

和 Extract 正好相反,也是用于處理聯(lián)合類型

// Exclude源碼
type Exclude<T, U> = T extends U ? never : T;
// 處理聯(lián)合類型
type Test1 = '1' | '2' | '3'

const obj: Exclude<Test1, '1' | '2'> = '3'; // 3 OK 賦值1,2就會error

8.ReturnType (函數(shù)的類型推導返回)

// ReturnType源碼
/**
 * Obtain the return type of a function type
 */
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

ReturnType案例

// 正確用法
const myFun = () => ({
    name: 'zhangsan',
    age: 233,
    sex: '1',
    tel: 123456789,
    fun: () => {
        return 233;
    },
    arr: [1,2,3,4,5,6]
});


type Test2 = ReturnType<typeof myFun>; // OK 鼠標放到Test2上可以發(fā)現(xiàn) 已推導出了myFun函數(shù)的返回類型。

// 錯誤用法
const someValue = 42;  
type InvalidReturnType = ReturnType<typeof someValue>; // error錯誤!someValue 不是一個函數(shù)。

9.NonNullable (類型中排除 null 和 undefined)

// 源碼
/**
 * Exclude null and undefined from T
 */
type NonNullable<T> = T & {}; // 源碼的這一句寫的很有意思,泛型參數(shù)T和{}的交集就默認排除了`null` 和 `undefined`

NonNullable的使用案例

type MaybeString = string | null | undefined;  
  
const value: MaybeString = getSomeStringValue(); // 假設這個函數(shù)可能返回一個字符串、null 或 undefined  
  
// 使用 NonNullable 確保 value 不會是 null 或 undefined  
const nonNullableValue: NonNullable<MaybeString> = value!; // 使用 ! 斷言操作符,或者通過其他方式確保值不為 null 或 undefined  
  
// 現(xiàn)在,nonNullableValue 的類型是 string,因為我們已經(jīng)排除了 null 和 undefined  
console.log(nonNullableValue.length); // 這是安全的,因為我們知道 nonNullableValue 一定是字符串

// 其實就是某些場景絕對為了排除null,undefined的類型才用的

作者:天渺工作室
鏈接:http://www.itdecent.cn/p/92f7a1cad1d7
來源:簡書
著作權歸作者所有。商業(yè)轉載請聯(lián)系作者獲得授權,非商業(yè)轉載請注明出處。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容