TS常用方法归纳

161 阅读2分钟

泛型

泛型是定义函数、接口或类等时,不预先给定类型的定义,而是在使用的时候根据传入的参数决定数据类型。

多个参数类型

   type Fn1 = {
      <T, Y>(a: T, b: Y): [Y, T]
   }
   
   const func: Fn1 = (a,b) => {
    return [b, a]
  }

泛型约束

在函数里使用泛型约束时,由于事先并不知道类型,所以不能随意操作它的类型或者方法。

function loggingIdentity<T>(arg: T): T {
    console.log(arg.length);
    return arg;
}

// index.ts(2,19): error TS2339: Property 'length' does not exist on type 'T'.

Partial

让所有属性变成可选?的属性

 /**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};

例如:
type Test = {
  a: number;
  b: string;
}

type TestPartial = Partial<Test>

其中TestPartial 等同于如下
type TestPartial = {  
   a?: number | undefined;  
   b?: string | undefined;  
}

Record

将第一个参数的所有值类型,采用第二个参数

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};

例如:
type Test = {
  a: number;
  b: string;
}

type Key1 = 'a1'|'b1'
type TestRecord = Record<Key1,Test>

其中TestRecord等同于
type TestRecord = {  
    a1: Test;  
    b1: Test;  
}

Pick

从第一个参数中,选择第二个参数需要的属性

/**
 * From T, pick a set of properties whose keys are in the union K
 */
type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};

例如
type Test = {
  a: number;
  b: string;
}

type TestPick = Pick<Test, 'a'>
其中TestPick等同于
type TestPick = {  
    a: number;  
}

Exclude

剔除第二个参数的属性


/**
 * Exclude from T those types that are assignable to U
 */
type Exclude<T, U> = T extends U ? never : T;

/**
 * Extract from T those types that are assignable to U
 */
type Extract<T, U> = T extends U ? T : never;


例如
type Test = 'a' |'b'|'a1'
type Key1 = 'a'

type TestExclude = Exclude<Test, Key1>
其中TestEclude等同于type TestExclude = "b" | "a1"

ReturnType

Required

/**
 * Make all properties in T required
 */
type Required<T> = {
    [P in keyof T]-?: T[P];
};

例如
type Test = {
  a?: number;
  b: string;
}

type TestRequired = Required<Test>
其中Test中的a属性是可选的,在TestRequired中变成了必输项,等同于

type TestExclude = {
    a: number;
    b: string;
}

ReadOnly


/**
 * Make all properties in T readonly
 */
type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

例如
type Test = {
  a?: number;
  b: string;
}

type TestReadonly = Readonly<Test>
其中TestReadonly等同于
type TestReadonly = {
    readonly a?: number | undefined;
    readonly b: string;
}

Omit


/**
 * Construct a type with the properties of T except for those in type K.
 */
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

例如
type Test = {
  a?: number;
  b: string;
}

type Key1 = 'a'
type TestOmit = Omit<Test, Key1>
其中TestOmit等同于
type TestOmit = {
    b: string;
}