问题
Let me preface this by saying that I am not sure if this is possible.
I am trying to obtain a constructor function that can be invoked with new that takes no parameters that calls a generic class's constructor that does take parameters. Like so:
class SimpleFoo {
public Key: String = null;
}
class GenericFoo<T> {
public Key: T = null;
constructor(private type: { new (): T }) {
this.Key = new this.type();
}
}
let simpleCtor: { new (): SimpleFoo } = SimpleFoo; // works
let simpleObj = new simpleCtor();
let genericCtor: { new (): GenericFoo<String> } = GenericFoo<String>(String); // <-- non-working code -- how to curry String parameter?
let genericObj = new genericCtor(); // this is how I wish to get a new object, no parameters involved
回答1:
I'm not sure what you're trying to do, but this seems to work:
type TypeConstructor<T> = { new (): T };
class GenericFoo<T> {
public Key: T = null;
constructor(private type: TypeConstructor<T>) {
this.Key = new this.type();
}
}
let genericCtor: { new (type: TypeConstructor<String>): GenericFoo<String> } = GenericFoo;
let genericObj = new genericCtor(String);
(code in playground)
Edit
If you don't want to pass the type when calling the ctor then you can bind the ctor to the wanted type and then call that bound ctor:
type BoundGenericFooConstructor<T> = { new(): GenericFoo<T> }
let genericCtor: BoundGenericFooConstructor<String> = GenericFoo.bind(null, String);
let genericObj = new genericCtor();
(code in playground)
来源:https://stackoverflow.com/questions/38694076/curried-constructor-of-generic-class