# 实用工具类型

TypeScript 提供了几种实用程序类型来促进常见的类型转换。这些实用程序在全局作用域内可用。

# Awaited<Type>

这种类型旨在模拟 async函数中的 await之类的操作,或 Promise上的 .then()方法 - 特别是它们递归解包 Promise的方式。

# 示例

type A = Awaited<Promise<string>>;

type B = Awaited<Promise<Promise<number>>>;

type C = Awaited<boolean | Promise<number>>;

# Partial&lt;Type&gt;

构造一个将 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",
});

# Required&lt;Type&gt;

构造一个由设置为 required 的 Type的所有属性组成的类型。与 Partial 相反。

# 示例

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

const obj: Props = { a: 5 };

const obj2: Required<Props> = { a: 5 };

# Readonly&lt;Type&gt;

构造一个将 Type的所有属性设置为 readonly的类型,这意味着构造类型的属性不能重新分配。

# 示例

interface Todo {
  title: string;
}

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

todo.title = "Hello";

此实用程序对于表示将在运行时失败的赋值表达式很有用(即尝试重新分配 冻结对象 的属性时)。

# Object.freeze

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

# Record&lt;Keys, Type&gt;

构造一个对象类型,其属性键为 Keys,其属性值为 Type。此实用程序可用于将一种类型的属性映射到另一种类型。

# 示例

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

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

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

cats.boris;

# Pick&lt;Type, Keys&gt;

通过从 Type中选取一组属性 Keys(字符串字面或字符串字面的并集)来构造一个类型。

# 示例

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

type TodoPreview = Pick<Todo, "title" | "completed">;

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

todo;

# Omit&lt;Type, Keys&gt;

通过从 Type中选择所有属性然后删除 Keys(字符串字面或字符串字面的并集)来构造一个类型。

# 示例

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

type TodoPreview = Omit<Todo, "description">;

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

todo;

type TodoInfo = Omit<Todo, "completed" | "createdAt">;

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

todoInfo;

# Exclude&lt;UnionType, ExcludedMembers&gt;

通过从 UnionType中排除所有可分配给 ExcludedMembers的联合成员来构造一个类型。

# 示例

type T0 = Exclude<"a" | "b" | "c", "a">;
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
type T2 = Exclude<string | number | (() => void), Function>;

# Extract&lt;Type, Union&gt;

通过从 Type中提取所有可分配给 Union的联合成员来构造一个类型。

# 示例

type T0 = Extract<"a" | "b" | "c", "a" | "f">;
type T1 = Extract<string | number | (() => void), Function>;

# NonNullable&lt;Type&gt;

通过从 Type中排除 nullundefined来构造一个类型。

# 示例

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

# Parameters&lt;Type&gt;

从函数类型 Type的参数中使用的类型构造元组类型。

# 示例

declare function f1(arg: { a: number; b: string }): void;

type T0 = Parameters<() => string>;
type T1 = Parameters<(s: string) => void>;
type T2 = Parameters<<T>(arg: T) => T>;
type T3 = Parameters<typeof f1>;
type T4 = Parameters<any>;
type T5 = Parameters<never>;
type T6 = Parameters<string>;
type T7 = Parameters<Function>;

# ConstructorParameters&lt;Type&gt;

从构造函数类型的类型构造元组或数组类型。它生成一个包含所有参数类型的元组类型(如果 Type不是函数,则生成类型 never)。

# 示例

type T0 = ConstructorParameters<ErrorConstructor>;
type T1 = ConstructorParameters<FunctionConstructor>;
type T2 = ConstructorParameters<RegExpConstructor>;
type T3 = ConstructorParameters<any>;

type T4 = ConstructorParameters<Function>;

# ReturnType&lt;Type&gt;

构造一个由函数 Type的返回类型组成的类型。

# 示例

declare function f1(): { a: number; b: string };

type T0 = ReturnType<() => string>;
type T1 = ReturnType<(s: string) => void>;
type T2 = ReturnType<<T>() => T>;
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
type T4 = ReturnType<typeof f1>;
type T5 = ReturnType<any>;
type T6 = ReturnType<never>;
type T7 = ReturnType<string>;
type T8 = ReturnType<Function>;

# InstanceType&lt;Type&gt;

构造一个由 Type中的构造函数的实例类型组成的类型。

# 示例

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

type T0 = InstanceType<typeof C>;
type T1 = InstanceType<any>;
type T2 = InstanceType<never>;
type T3 = InstanceType<string>;
type T4 = InstanceType<Function>;

# ThisParameterType&lt;Type&gt;

提取函数类型的 参数的类型,如果函数类型没有 this参数,则提取 未知

# 示例

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

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

# OmitThisParameter&lt;Type&gt;

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&lt;Type&gt;

此实用程序不返回转换后的类型。相反,它用作上下文 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&gt;的上下文类型,因此 methods对象内的方法中的 类型是 { x: number, y: number } & { moveBy(dx: number, dy: number): number }。请注意 methods属性的类型如何同时是方法中 this类型的推理目标和源。

ThisType<T&gt;标记接口只是在 lib.d.ts中声明的一个空接口。除了在对象字面的上下文类型中被识别之外,接口的行为就像任何空接口。

# 内在字符串操作类型

# Uppercase&lt;StringType&gt;

# Lowercase&lt;StringType&gt;

# Capitalize&lt;StringType&gt;

# Uncapitalize&lt;StringType&gt;

为了帮助围绕模板字符串字面进行字符串操作,TypeScript 包含一组可用于类型系统内的字符串操作的类型。您可以在 模板字面类型 文档中找到这些内容。

Last Updated: 5/25/2023, 2:35:11 PM