We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Cnotes • 3 years ago

I'm very disappointed.

const model = factory.create<t>(args);

is the goal, this isn't even useful at all.

Dmitry • 7 years ago

What if I need to create generic type instance within generic class?

class BaseService<T>{
...
private foo() {
let bar: T;
bar = ...
}
}

In this case Factory.create(T) will not work - "T only refers to a type, but is being used as value here"

Rico Suter • 7 years ago

In this case, you need to pass the type factory as constructor parameter:

constructor(type: (new () => T)) { this.type = type; }

and use it in the method:

foo() { let bar = new this.type(); }
Justin • 7 years ago

I needed to instantiate a generic type so I tried your code constructor(type: (new () => T)) { this.type = type; } and I'm getting build errors that it can't resolve all the parameters for the class

stampr_cory • 5 years ago

the errors were likely because you have to include the same arguments in new that the generic type accepts. e.g. class Person { ctor(hello: string) } Generic<person> { ctor(type: new (hello: string) => T) {} }

note the "hello: string" on both.

Rico Suter • 7 years ago

I don't understand your scenario, but in your case T is not defined maybe you want to define it as the type of the class?

philippfx • 7 years ago

Can you give a complete example please?

Rico Suter • 7 years ago

I've updated the sample code with a Person class and console.log, you can directly try this in http://www.typescriptlang.o...

Dmitry • 7 years ago

Yes, with constructor this works! thanks)

Andy Nunes • 6 years ago

This is very helpful, thanks for writing it up!

Siva Nomula • 8 years ago

Thanks!!! here is the sample code code the dynamic response

getData() {

return this.http

.get(url, { headers: this.headers })

.map(p => this.handleResponse(p, ReportReviewSummary))

.catch(this.handleError);

}

private handleResponse(response: any, type: (new (any) => T)): T {

if (response.text() === '') {

return new type(null);

} else {

return new type(response.json());

}

}

Philippfx • 8 years ago

Great article :-)

How can I apply your strategy for array T[] ?

Best regards,
Philippfx

Rico Suter • 8 years ago

Just cast a new array to T? E.g. let myArray = <T[]>[] and fill it with objects created with the method above... however, I think the type T[] cannot be expressed in the JavaScript type system directly.