使用泛型函数中的参数类型创建一个新实例

Create a new instance using the type of a parameter in generic function

我实现了一个通用函数来将选项与默认选项合并:

  // definition
  protected defaultOptions<T>(options: T, type: new () => T): T {
    return {
      ...options,
      ...new type(),
    };
  }

它就像一个魅力,但我总是需要将类型作为第二个参数传递:

  // use it like this
  upload(file: File, options: FilesUploadOptions) {
    options = this.defaultOptions(options, FilesUploadOptions);
    ...
    ...
  }

问题:

有一种方法可以实现相同的结果,但是删除方法 defaultOptions 的第二个参数并使用第一个参数的类型获取和创建新实例?

  // definition
  protected defaultOptions<T>(options: T): T {

    const type = ???????; // some smart type generics here :)

    return {
      ...options,
      ...new type(),
    };
  }

这样我就可以像这样简单地使用它:

  upload(file: File, options: FilesUploadOptions) {
    options = this.defaultOptions(options);
    ...
    ...
  }

谢谢!

There is a way to achieve the same result, but removing the second parameter of the method defaultOptions and get and create new instance with the type from the first parameter?

不,那不可能。在 TypeScript 中,类型是纯粹的编译时构造。编译为 JavaScript 时,它们将被删除。这意味着无法在运行时访问它们。