工具类型

Typescript 提供了一些工具,来辅助进行常见的类型转换。这些类型全局可用。

Awaited<Type>

此类型用于对 async 异步函数中的 await 上,或应用于 Promise 递归展开 .then() 方法上。

type A = Awaited<Promise<string>>;
// type A = string
 
type B = Awaited<Promise<Promise<number>>>;
// type B = number
 
type C = Awaited<boolean | Promise<number>>;
// type C = number | boolean


Partial<Type>

用于构造一个类型,类型的所有属性都设置为 可选 。这个工具返回代表给定类型的所有子集的类型。

interface Todo {
  title: string;
  description: string;
}

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}

const todo1 = {
  title: "organize desk",
  description: "clear clutter",
};

const todo2 = updateTodo(todo1, {
  description: "throw out trash",
  // description?: string | underfined
});

/*
const todo2: {
  title: string;
  description: string;
}
*/


Required<Type>

用于构造一个类型,类型的所有属性都设置为 必填 的类型。这个工具类型跟 Partial 相反。

interface Props {
  a?: number;
  b?: string;
}

const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 };
// TypeError: Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.


Readonly<Type>

用于构造一个类型,类型的所有属性都设置为 readonly 的类型。意味着这个类型的所有的属性全都不可以重新赋值。

interface Todo {
  title: string;
}

const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};

todo.title = "Hello";
// TypeError: Cannot assign to 'title' because it is a read-only property.

这个工具类型用于表示在运行时失败的赋值表达式(即尝试重新分配冻结对象的属性时)。

Object.freeze
function freeze<Type>(obj: Type): Readonly<Type>;


Record<Keys, Type>

用于构造一个对象类型,它所有的键都是 Keys 类型,它所有的值都是 Type 类型。这个工具类型可以被用于映射一个类型的属性到另一个类型。

interface CatInfo {
  age: number;
  breed: string;
}

type CatName = "miffy" | "boris" | "mordred";

const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  // (property) miffy: CatInfo
  boris: { age: 5, breed: "Maine Coon" },
  // (property) boris: CatInfo
  mordred: { age: 16, breed: "British Shorthair" },
  // (property) mordred: CatInfo
};
// const cats: Record<CatName, CatInfo>


Pick<Type, Keys>

用于构造一个类型,它是从 Type 类型里面, 挑选出 属性 Keys<、var> (Keys是字符串字面量或者字符串字面量的联合类型)

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

type TodoPreview = Pick<Todo, "title" | "completed">;
/*
type TodoPreview = {
  title: string;
  completed: boolean;
}
*/

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

todo;
// const todo: TodoPreview


Omit<Type, Keys>

用于构造一个类型,它是从 Type 类型里面, 过滤掉 属性 Keys (Keys 是字符串字面量或者字符串字面量的联合类型)

interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}

type TodoPreview = Omit<Todo, "description">;
/*
type TodoPreview ={
  title: string;
  completed: boolean;
  createdAt: number;
}
*/

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
  createdAt: 1615544252770,
};

todo;
// const todo: TodoPreview


type TodoInfo = Omit<Todo, "completed" | "createdAt">;
/*
type TodoInfo = {
  title: string;
  description: string;
}
*/

const todoInfo: TodoInfo = {
  title: "Pick up kids",
  description: "Kindergarten closes at 5pm",
};

todoInfo;
// const todoInfo: TodoInfo


Exclude<UnionType, ExcludedMembers>

用于构造一个类型,它是从 UnionType 联合类型里面, 排除 所有 ExcludedMembers 类型。

type T0 = Exclude<"a" | "b" | "c", "a">;
// type T0 = "b" | "c"

type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
// type T1 = "c"

type T2 = Exclude<string | number | (() => void), Function>;
// type T2 = string | number


Extract<Type, Union>

用于构造一个类型,它是从 Type 类型里面, 提取 所有 Union 类型。

type T0 = Extract<"a" | "b" | "c", "a" | "f">;
// type T0 = "a"

type T1 = Extract<string | number | (() => void), Function>;
// type T1 = () => void


NonNullable<Type>

用于构造一个类型,从 Type 中, 排除 所有的 null undefined 类型。

type T0 = NonNullable<string | number | undefined>;
// type T0 = string | number

type T1 = NonNullable<string[] | null | undefined>;
// type T1 = string[]


Parameters<Type>

根据所有 Type 中,函数的参数类型,构造一个元组类型。

type T0 = Parameters<() => string>;
// type T0 = []

type T1 = Parameters<(s: string) => void>;
// type T1 = [s: string]

type T2 = Parameters<<T>(arg: T) => T>;
// type T2 = [arg: unknown]
declare function f1(arg: { a: number; b: string }): void;
type T3 = Parameters<typeof f1>;
/*
type T3 = [arg: {
   a: number;
   b: string;
}]
*/

type T4 = Parameters<any>;
// type T4 = unknown[]

type T5 = Parameters<never>;
// type T5 = never

type T6 = Parameters<string>;
// TypeError: Type 'string' does not satisfy the constraint '(...args: any) => any'.
// type T6 = never

type T7 = Parameters<Function>;
// TypeError: Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.
// type T7 = never


ConstructorParameters<Type>

根据 Type 中,构造函数类型,来构造一个元组或数组类型。它产生一个带着所有参数类型的元组。如果 Type 不是一个函数,则返回 never

在 TypeScript 标准库中,内置有构造签名的实际构造函数: interface ErrorConstructor interface FunctionConstructor interface RegExpConstructor 类型。

type T0 = ConstructorParameters<ErrorConstructor>;
// type T0 = [message?: string]

type T1 = ConstructorParameters<FunctionConstructor>;
// type T1 = string[]

type T2 = ConstructorParameters<RegExpConstructor>;
// type T2 = [pattern: string | RegExp, flags?: string]

type T3 = ConstructorParameters<any>;
// type T3 = unknown[]

type T4 = ConstructorParameters<Function>;
// TypeError: Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.
// type T4 = never


ReturnType<Type>

用于构造一个由 Type 中函数的返回值的类型,组成的类型。

type T0 = ReturnType<() => string>;
// type T0 = string

type T1 = ReturnType<(s: string) => void>;
// type T1 = void

type T2 = ReturnType<<T>() => T>;
// type T2 = unknown

type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
// type T3 = number[]
declare function f1(): { a: number; b: string };

type T4 = ReturnType<typeof f1>;
/*
type T4 = {
   a: number;
   b: string;
}
*/

type T5 = ReturnType<any>;
// type T5 = any

type T6 = ReturnType<never>;
// type T6 = never

type T7 = ReturnType<string>;
// TypeError: Type 'string' does not satisfy the constraint '(...args: any) => any'.
// type T7 = any

type T8 = ReturnType<Function>;
// TypeError: Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.
// type T8 = any


InstanceType<Type>

用于构造一个由所有 Type 中构造函数的实例类型,组成的类型。

class C {
  x = 0;
  y = 0;
}

type T0 = InstanceType<typeof C>;
// type T0 = C

type T1 = InstanceType<any>;
// type T1 = any

type T2 = InstanceType<never>;
// type T2 = never

type T3 = InstanceType<string>;
// TypeError: Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
// type T3 = any

type T4 = InstanceType<Function>;
// TypeError: Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.
// type T4 = any


ThisParameterType<Type>

用于 提取 函数的 this 参数的类型。如果这个函数没有 this 参数,则返回 unknown 类型。

function toHex(this: Number) {
  return this.toString(16);
}

function numberToString(n: ThisParameterType<typeof toHex>) {
  return toHex.apply(n);
  // (parameter) n: number
}


OmitThisParameter<Type>

用于 移除 函数的 this 参数的类型。如果 Type 没有明确的声明 this 类型,那么这个返回的结果就是 Type ,不然的话,就返回一个新的函数类型,基于 Type ,但不再有 this 参数。泛型会被抹去,只有最后重载的签名被传播进了返回的新的函数类型。

function toHex(this: Number) {
 return this.toString(16);
}

const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);

console.log(fiveToHex());


ThisType<Type>

这个类型不返回一个转换过的类型,它被用作标记一个上下文的 this 类型。注意:如果想使用这个工具类型, noImplicitThis 选项,必须启用。

type ObjectDescriptor<D, M> = {
  data?: D;
  methods?: M & ThisType<D & M>; // Type of 'this' in methods is D & M
};

function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
  let data: object = desc.data || {};
  let methods: object = desc.methods || {};
  return { ...data, ...methods } as D & M;
}

let obj = makeObject({
  data: { x: 0, y: 0 },
  methods: {
    moveBy(dx: number, dy: number) {
      this.x += dx; // Strongly typed this
      this.y += dy; // Strongly typed this
    },
  },
});

obj.x = 10;
obj.y = 20;
obj.moveBy(5, 5);

在上面的例子中, makeObject 函数的参数重 methods 对象有上下文的类型包含了 ThisType<D & M> ,因此 methods 方法中的 this 类型是 {x: number, y: number}&{moveBy(dx: number, dy: number): number} 。注意 methods 的类型是怎么同时成为一个接口的目标和方法中 this 类型的源。

ThisType<T> 标记的接口是一个生命在 lib.d.ts 中的简单的空接口。除了被认为是一个对象字面量的上下文类型,这个接口表现得就像一个空接口。


内置字符操作类型

  • Uppercase<StringType>
  • Lowercase<StringType>
  • Capitalize<StringType>
  • Uncapitalize<StringType>

为了帮助围绕模版字符串的字符串处理,TypeScript 的类型系统包含了一系列中可以用于字符串操作的类型。你可以在文档 模板字面量类型 中找到这些。