本文介绍了Curried构造函数的泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我先说这个,说我不知道​​这是否可能。

Let me preface this by saying that I am not sure if this is possible.

我试图获取一个构造函数,可以使用new调用一个参数,该函数不调用一个通用类的构造函数。像这样:

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


推荐答案

我不知道你想要做什么,但这似乎工作:

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);

()

如果您不想在调用ctor,那么你可以将ctor绑定到想要的类型,然后调用该绑定的ctor:

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();

()

这篇关于Curried构造函数的泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 09:29