泛型 class 的 Curried 构造函数
Curried constructor of generic class
首先让我说我不确定这是否可能。
我正在尝试获取一个可以用 new 调用的构造函数,它不带参数,调用通用 class 的带参数的构造函数。像这样:
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
我不确定你想做什么,但这似乎有效:
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);
编辑
如果你不想在调用构造函数时传递类型,那么你可以将构造函数绑定到想要的类型,然后调用绑定的构造函数:
type BoundGenericFooConstructor<T> = { new(): GenericFoo<T> }
let genericCtor: BoundGenericFooConstructor<String> = GenericFoo.bind(null, String);
let genericObj = new genericCtor();
首先让我说我不确定这是否可能。
我正在尝试获取一个可以用 new 调用的构造函数,它不带参数,调用通用 class 的带参数的构造函数。像这样:
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
我不确定你想做什么,但这似乎有效:
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);
编辑
如果你不想在调用构造函数时传递类型,那么你可以将构造函数绑定到想要的类型,然后调用绑定的构造函数:
type BoundGenericFooConstructor<T> = { new(): GenericFoo<T> }
let genericCtor: BoundGenericFooConstructor<String> = GenericFoo.bind(null, String);
let genericObj = new genericCtor();