首页 > 解决方案 > 映射`ConstructorParameters` 元组到对象类型

问题描述

我想知道是否有任何方法可以映射ConstructorParameters<T>到一个对象,其中每个键是参数名称,键是参数的类型。

我的意思是,鉴于:

class User {
  public id: number;

  constructor(
      public readonly name: string,
      public readonly surname: string,
  ) {}

  get fullname(): string { ... }
  public isAdmin(): boolean { ... }
}

随着ConstructorParameters<typeof User>我得到类型[name: string, surname: string]。也许这可以映射到以下类型{ name: string, surname: string }请注意,类型应该省略: id, fullname&isAdmin因为它们不存在于构造函数中。

我见过https://stackoverflow.com/a/49062616这是一个非常酷的解决方案,但它与构造函数中不存在的 getter 和公共属性中断。

标签: typescript

解决方案


我不这么认为。函数参数的“名称”实际上在函数上下文之外没有任何意义。例如,您可以这样做:

type FuncType = (foo: string) => void;

const MyFunc: FuncType = (bar) => {
  return bar;
}

fooand的“名称”bar根本不匹配,但顺序类型匹配,这才是真正重要的。可能类似于如何解构数组并为项目指定任意名称;数组中的项目没有开头的名称:

const array = [1, 2, 3];
const [one, two, three] = array;

您可能得到的最接近的方法是将构造函数的顺序和类型作为对象获取,但我不确定这会有什么用:

type ConstructorParametersIndices<T extends new (...args: any) => any> =
  T extends new (...args: infer P) => any ? {[K in keyof P]: K} : never;

type A = ConstructorParameters<typeof User>;
// [name: string, surname: string]

type B = ConstructorParametersIndices<typeof User>;
// [name: "0", surname: "1"]

type C = {[P in B[number] as P]: A[P]};
/*  {
 *    0: string;
 *    1: string;
/*  }

推荐阅读