Curried constructor of generic class

时光怂恿深爱的人放手 提交于 2019-12-25 08:26:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!