Typescript常用高级类型总结

217 阅读2分钟

Typescript常用高级类型

Record

以 typeof 格式快速创建一个类型,此类型包含一组指定的属性且都是必填。

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

// 等同于
type Coord = {
  x: number;
  y: number;
}

Partial

将类型定义的所有属性都修改为可选。

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

type Coord = Partial<Record<'x' | 'y', number>>;

// 等同于
type Coord = {
  x?: number;
  y?: number;
}

Readonly

将所有属性定义为只读。

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

type Coord = Readonly<Record<'x' | 'y', number>>;

// 等同于
type Coord = {
    readonly x: number;
    readonly x: number;
}

// 如果进行了修改,则会报错:
const c: Coord = { x: 1, y: 1 };
c.x = 2; // Error: Cannot assign to 'x' because it is a read-only property.

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 Coord = Record<'x' | 'y', number>;
type CoordX = Pick<Coord, 'x'>;

// 等用于
type CoordX = {
  x: number;
}

Required<T>

Partial<T> 程序类型的作用相反,将类型属性都变成必填。

/**
 * Make all properties in T required
 * 主要是因为 -? 映射条件的装饰符的能力,去掉了所有可选参数状态
 */
type Required<T> = {
    [P in keyof T]-?: T[P];
};

type Coord = Required<{ x: number, y?:number }>;

// 等同于
type Coord = {
  x: number;
  y: number;
}

Exclude<T,U>

排除一个 联合类型 中指定的子类型。

主要是基于 extends 条件类型的解析推迟的特性,返回了匹配之外的所有 候选类型,配合 never 类型 的空值特性,实现了这一高级类型。

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

type T0 = Exclude<'a' | 'b' | 'c', 'b'> // 'a' | 'c'
type T1 = Exclude<string | number | boolean, boolean> // string | number

Extract<T,U>

与 Exclude<T, U> 完全相反的功能,用于提取指定的 联合类型,如果不存在提取类型,则返回never。可以用在判断一个复杂的 联合类型 中是否包含指定子类型

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

type T0 = Extract<'a' | 'b' | 'c', 'a'> // 'a'
type T1 = Extract<string | number | boolean, boolean> // boolean

Omit<T,K extends keyof any>

排除接口中指定的属性。

/**
 * 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>>;

interface I1 {
  a: number;
  b: string;
  c: boolean;
}

type AC = Omit<I1, 'b'>;     // { a:number; c:boolean } 
type C = Omit<I1, 'a' |'b'>  // { c: boolean }

NonNullable

过滤掉 联合类型 中的 null 和 undefined 类型。