We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.
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"
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(); }
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
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.
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?
Can you give a complete example please?
I've updated the sample code with a Person class and console.log, you can directly try this in http://www.typescriptlang.o...
Yes, with constructor this works! thanks)
This is very helpful, thanks for writing it up!
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());
}
}
Great article :-)
How can I apply your strategy for array T[] ?
Best regards,
Philippfx
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.
I'm very disappointed.
const model = factory.create<t>(args);
is the goal, this isn't even useful at all.