Typescript高級用法 keyof,Pick,Record,Partial,Required,Exclude,Omit?


記錄一下typescript中一些類型高級用法:

首先聲明一個類型IUser:

interface IUser {
  name: string;
  age?: number;
  class?: string;
  sex: string;
}

1、keyof:作用是獲取鍵

type keys = keyof IUser;

2、Pick:從類型定義的屬性中,選取指定一組屬性,返回一個新的類型定義。

源碼:

type Pick<T, K extends keyof T> = {[P in K]: T[P]};

例子:

type IPG = Pick<IUser, 'name'>
let gg: IPG = {
  name: '5'
}

3、Record:以 typeof 格式快速創建一個類型,此類型包含一組指定的屬性且都是必填。

源碼:

type Record<K extends keyof any, T> = {[P in K]: T};

例子:

type IRH = Record<keyof IUser, string>
let hh: IRH = {
  name: '6',
  age: '6',
  class: '6',
  sex: '0'
}

4、Partial: 將傳入的屬性變為可選項

源碼:

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

例子:

type IPB = Partial<IUser>;

let bb: IPB = {
  name: '1',
  age: 1
}

5、Required:將傳入的屬性變為必選項

源碼:

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

例子:

type IRC = Required<IUser>;

let cc: IRC = {
  name: '2',
  age: 2,
  class: '2',
  sex: '0'
}

6、Exclude :的作用是兩個參數對比過濾出前面參數獨有的。

源碼:

type Exclude<T, U> = T extends U ? never : T;

例子:

type IED = '1' | '2' | '3';
type IEE = '4';
let dd: Exclude<IED, IEE> = '1'

7、Omit :的作用是將前面參數中后面的屬性過濾掉

源碼:

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

例子:

type IOF = Omit<IUser, 'sex'>
let ff: IOF = {
  name: '4',
  age: 4,
  class: '4',
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM