首发于 前端知识

Typescript系列-进阶1

类型转换(Utility Types)

Awaited<Type>

// 有一个 Promise 对象,这个 Promise 对象会返回一个类型。
// 在 TS 中,我们用 Promise<T> 中的 T 来描述这个 Promise 返回的类型。
type APromiseType = Promise<string>
type A = Awaited<ExampleType> // string
// 也可以递归地展开promise的方式
type BPromiseType = Promise<Promise<number>>;
type B = Awaited<BPromiseType>; // number

Partial<Type>

// 构造一个将type的所有属性设置为可选的类型。此实用程序将返回表示给定类型的所有子集的类型。
type Partial<T> = {
    [P in keyof T]?: T[P];
// 定义一个接口
interface Person {
  name: string;
  age: number;
  location: string;
// 转换
type PartialPerson = Partial<Person>;
// 转换后结果:
interface PartialPerson {
  name?: string;
  age?: number;
  location?: string;
}

Required<Type>

// 构造一个将type的所有属性设置为必选的类型。与Partial相反。
// 注意,在strictNullChecks模式中,当同态映射类型删除?修饰符,它也会从该属性的类型中移除undefined:
type Required<T> = { 
  [P in keyof T]-?: T[P]
// 定义一个接口
type Foo = { 
  a?: string 
}; // { a?: string | undefined }
// 转义结果
type Bar = Required<Foo>; // { a: string }

Readonly<Type>

// 构造一个将type的所有属性设置为只读的类型,这意味着不能重新分配所构造类型的属性
type Readonly<T> = {
  readonly [P in keyof T]: T[P];
// 定义一个接口
interface Todo {
  title: string;
// 转义 
const todo: Readonly<Todo> = {
  title: "Delete inactive users",
// 可读属性不可重新赋值 todo.title = "Hello";

Record<Keys, Type>

// 用于将类型的属性映射到另一类型
type Record<K extends keyof any, T> = {
    [P in K]: T;
// 定义一个接口
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" },
};

Pick<Type, Keys>

// 从一个复合类型中,取出几个想要的类型的组合
type Pick<T, K extends keyof T> = {
  [key in K]: T[key]
// 定义一个接口
interface Person {
  name: string;
  age: number;
  location: string;
// 转义 生成的新类型不能声明为接口
type PersonType = pick(person, "name", "age"); // { name: string, age: number }

Omit<Type, Keys>

// 以一个类型为基础支持剔除某些属性,然后返回一个新类型。
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
// 定义一个接口
interface Person {
  name: string;
  age: number;
  location: string;
// 转义
type PersonType = Omit<Todo, "location">;
// 结果
type PersonType = {
  name: string;
  age: number;
};

Exclude<UnionType, ExcludedMembers>

// 帮助我们把 T 类型当中属于 U 类型的部分去除后得到一个新的类型
type Exclude<T, U> = T extends U ? never : T;
// 转义
type T0 = Exclude<"a" | "b" | "c", "a">; 
// 结果
type T0 = "b" | "c";

Extract<Type, Union>

// 用于从类型T中取出可分配给U类型的成员
type Extract<T, U> = T extends U ? T : never;
// 转义
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
type T1 = Extract<string | number | (() => void), Function>;
// 结果     
type T0 = "a"
type T1 = () => void

NonNullable<Type>

// 通过从T中排除null和undefined来构造新类型
type NonNullable<T> = T extends null | undefined ? never : T
// 转义
type T0 = NonNullable<string | number | undefined>;
type T1 = NonNullable<string[] | null | undefined>;
// 结果   
type T0 = string | number
type T1 = string[]

Parameters<Type>

// 获取函数T的形参,构造元组类型。
type Parameters<T extends Function> = ((...args: infer U) => any) | (new (...args: infer U) => any) ? U : any[];
// 示例
declare function f1(arg: { a: number; b: string }): void;
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]
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>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T6 = never
type T7 = Parameters<Function>;
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>

// 获取构造函数入参类型的,生成一个包含所有参数类型的元组类型。如果T不是函数,则生成类型never。
type ConstructorParameters<T extends new (...args: any) => any> = T extends new (...args: infer P) => any ? P : never;
// 示例
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>;
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>

// 构造由函数T的返回类型组成的新类型
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
// 示例
declare function f1(): { a: number; b: string };
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[]
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>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T7 = any
type T8 = ReturnType<Function>;
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>

// 构造由T中的构造函数的实例类型组成的类型
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
// 示例
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>;
Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
type T3 = any
type T4 = InstanceType<Function>;
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>

// 提取函数T的this参数的类型,如果函数类型没有this参数则为unknown。
type ThisParameterType<T> = T extends (this: unknown, ...args: any[]) => any
  T extends (this: infer U, ...args: any[]) => any
  : unknown
// 示例
function toHex(this: Number) {
  return this.toString(16);
function numberToString(n: ThisParameterType<typeof toHex>) {
  return toHex.apply(n);
}

OmitThisParameter<Type>

// 从T中移除this参数,如果T没有显式声明此参数,则结果只是T,否则,从T创建一个不带此参数的新函数类型。泛型被删除,只有最后一个重载签名被传播到新的函数类型中。
type OmitThisParameter<T> = unknown extends ThisParameterType<T> ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T;
// 示例
function toHex(this: Number) {
  return this.toString(16);
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
console.log(fiveToHex());

ThisType<Type>

// 此实用程序不返回转换后的类型。相反,它作为上下文这类类型的标记。注意,必须启用noImplicitThis标志才能使用这个实用程序。
interface ThisType<T> { }
// 示例
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