TS 中的類型驗算- 高級通用 API 實現

由於現在工作使用的技術棧是 ReactTypeScriptahooks,工作中需要用到大量的類型定義,特此記錄一下一些常用的類型通用 API 封裝。

TS 內置類型

TS 內置關鍵字

TS compiler 內部實現的類型

實現 Optional API,實現部分類型變爲可選

type Article = {
  title: string;
  content: string;
  author: string;
  date: Date;
  readCount: number;
}
// 實現 T 部分類型變爲可選
type Optional<T,K extends keyof T> = Omit<T,K> & Partial<Pick<T,K>>; 
type ArticleTodo = Optional<Article,'author' | 'date' | 'readCount'>
// { title: string; content: string; author?: string; date?: Date; readCount?: number; }

實現 GetOptional API,獲取類型中的所有可選字段

type Article = {
  title: string;
  content: string;
  author?: string;
  date?: Date;
  readCount?: number;
}
// 獲取 T 類型中的所有可選字段
type GetOptional<T> = {
  [P in keyof T as T[P] extends Required<T>[P] ? never : P]: T[P]
};
type ArticleTodo = GetOptional<Article>
// { author?: string; date?: Date; readCount?: number; }

實現 DeepReadonly API,實現不可變類型的深度遍歷

type Article = {
  title: string;
  name:{
    first:string;
    lasr:string;
  }
}
// API,實現不可變類型的深度遍歷
type DeepReadonly<T extends Record<string | symbol,any>> = {
  readonly [k in keyof T]: DeepReadonly<T[K]>;
};
type ArticleTodo = DeepReadonly<Article>

實現 UnionToIntersection API,將聯合類型轉爲交叉類型

type Article = { title:string } | { name:string } | { date: Date }
// API,將聯合類型轉爲交叉類型
type UnionToIntersection<T> = 
  (T extends any ? (x: T) => any : never) extends (x: infer R) => any ? R : never;
type ArticleTodo = UnionToIntersection<Article>
// { title:string } & { name:string } & { date: Date }
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/6wiaqmlU2Es0DohJiCbh-g