Typescript型別推斷技巧你知道麼?

楊明明發表於2018-10-17

extends 繼承

export type Extends<T,U> = T extends U;
複製程式碼

readonly 只讀

export type Readonly<T> = { readonly [P in keyof T]: T[P] };
複製程式碼

is

export type IsType<T> = (val: any) => val is T;
複製程式碼

場景:判斷是否屬於某個或某類值

// 是否object
export const isObj: IsType<object>;
// 是否number
export const isNumber: IsType<number>;
// 是否string
export const isString: IsType<string>;
複製程式碼

keyof 鍵值

export type KeyOf<T> = keyof T;
複製程式碼

利用K extends keyof WindowEventMap將引數type:K限制在WindowEventMap的鍵值列表,listener中的引數ev限定為WindowEventMap對應K相應的值

declare function addEventListener<K extends keyof WindowEventMap>(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
複製程式碼

in 在*中

export type Partial<T> = { [P in keyof T]?: T[P] };
複製程式碼

? 二義符

export type Extract<T, U> = T extends U ? T : never;
複製程式碼

& 合併

export type Merge<T,U> = T & U;
複製程式碼

實用

export type IsType<T = any> = (val: any) => val is T;
export type KeyOf<T> = keyof T;
export type Defaultize<P, D> = P extends any
  ? string extends keyof P
    ? P
    : Pick<P, Exclude<keyof P, keyof D>> &
        Partial<Pick<P, Extract<keyof P, keyof D>>> &
        Partial<Pick<D, Exclude<keyof D, keyof P>>>
  : never;
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type Matching<InjectedProps, DecorationTargetProps> = {
  [P in keyof DecorationTargetProps]: P extends keyof InjectedProps
    ? InjectedProps[P] extends DecorationTargetProps[P]
      ? DecorationTargetProps[P]
      : InjectedProps[P]
    : DecorationTargetProps[P]
};

export type MergePropTypes<P, T> = P & Pick<T, Exclude<keyof T, keyof P>>;
export type Partial<T> = { [P in keyof T]?: T[P] };
export type Required<T> = { [P in keyof T]-?: T[P] };
export type Readonly<T> = { readonly [P in keyof T]: T[P] };
export type Pick<T, K extends keyof T> = { [P in K]: T[P] };
export type Record<K extends keyof any, T> = { [P in K]: T };
export type Exclude<T, U> = T extends U ? never : T;
export type Extract<T, U> = T extends U ? T : never;
export type NonNullable<T> = T extends null | undefined ? never : T;


export type ReturnType<T extends (...args: any[]) => any> = T extends (
  ...args: any[]
) => infer R
  ? R
  : any;
export type InstanceType<
  T extends new (...args: any[]) => any
> = T extends new (...args: any[]) => infer R ? R : any;
複製程式碼

相關文章