泛型类的Curried构造函数

时间:2016-08-01 08:23:02

标签: typescript constructor currying

让我先说明我不确定这是否可行。

我正在尝试获取一个可以使用new调用的构造函数,该函数不接受调用泛型类的构造函数的参数。像这样:

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 个答案:

答案 0 :(得分:0)

我不确定你要做什么,但这似乎有效:

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

修改

如果您不想在调用ctor时传递该类型,那么您可以将ctor绑定到所需类型,然后调用该绑定的ctor:

type BoundGenericFooConstructor<T> = { new(): GenericFoo<T> }

let genericCtor: BoundGenericFooConstructor<String> = GenericFoo.bind(null, String);
let genericObj = new genericCtor();

code in playground