Generics 我能告诉TypeScript泛型类型有一个构造函数吗?

Generics 我能告诉TypeScript泛型类型有一个构造函数吗?,generics,typescript,Generics,Typescript,我想我可以这样做来创建TypeScript中泛型的新实例: class Tree<T extends SomeInterface> { constructor(private elementType: {new(): T}) { } public Grow() { var newElement: T = new this.elementType(); // ... } } 但是有没有办法让TypeScript知道泛

我想我可以这样做来创建TypeScript中泛型的新实例:

class Tree<T extends SomeInterface> {

    constructor(private elementType: {new(): T}) {
    }

    public Grow() {
        var newElement: T = new this.elementType();
        // ...
    }
}
但是有没有办法让TypeScript知道泛型有一个新的()?换句话说,有没有办法让这样的东西发挥作用

class Tree<T extends SomeInterface> { // <-- Modify the constraint?
    public Grow() {
        var newElement: T = new T();
        // ...
    }
}
不完全是。原因是您仍然需要传入将为您创建新对象的实体。您不能仅将编译时约束
用作运行时
新t

interface SomeInterface{    
}

interface SomeInterfaceConstructor<T extends SomeInterface>{
    new (): T;
}


class Tree<T extends SomeInterface> {
    constructor(private elementType: SomeInterfaceConstructor<T>) {
    }
    public Grow() {
        var newElement = new this.elementType();
        // ...
    }
}
interface SomeInterface{
}
接口SomeInterfaceConstructor{
新的():T;
}
类树{
构造函数(私有元素类型:SomeInterfaceConstructor){
}
公众成长(){
var newElement=newthis.elementType();
// ...
}
}

您可以在约束中使用构造签名类型。但是
T
是打算作为构造函数的类型,还是
new
ing某个值的结果的类型?在发布的示例中,您正在以两种方式使用它。我已经证明了这一点。希望你能找到解决办法。正如我从文档()中得到的,您不能在约束中使用类型参数,比如:“函数find(n:t,s:U){…”。所以在我看来,答案似乎是“No”关于你的问题有一段时间了。@RyanCavanaugh T打算成为结果的类型……我想我现在从你的问题中意识到,
new
是在构造函数上调用的,而不是在“类型”上调用的。所以我想为了得到我想要的结果,我必须创建某种
Createable
接口,并给它一个
create()
功能?