manzapanza
manzapanza

Reputation: 6215

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!

Upvotes: 1

Views: 104

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152880

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.

Upvotes: 1

Related Questions