简体   繁体   中英

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

I implemented a generic function to merge options with default options:

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

It works like a charm but I always need to pass the type as second parameter:

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

Question:

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?

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

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

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

In this way I could use it simply like this:

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

Thanks!

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?

No that's not possible. In TypeScript, types are a purely compile time construct. When compiling to JavaScript they are removed. This means there's no way to access them during runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM