在typescript中,如何在基类中的静态函数中返回子类实例?

在typescript中,如何在基类中的静态函数中返回子类实例?,typescript,typescript-generics,Typescript,Typescript Generics,这是我的密码: 类基元素{ 公共静态createthis:T:InstanceType{ 这个.createHelper; const r=新的; 返回r; } 公共静态createHelper{ //省略了实现。 } } 我希望静态create函数将返回一个与此相同的当前类型的实例 但它不起作用: Type 'BaseElement' is not assignable to type 'InstanceType<T>'. 如何修复上述代码的类型注释?提前谢谢 -------更新

这是我的密码:

类基元素{ 公共静态createthis:T:InstanceType{ 这个.createHelper; const r=新的; 返回r; } 公共静态createHelper{ //省略了实现。 } } 我希望静态create函数将返回一个与此相同的当前类型的实例

但它不起作用:

Type 'BaseElement' is not assignable to type 'InstanceType<T>'.
如何修复上述代码的类型注释?提前谢谢

-------更新--------


看来现在不可能了,除非在公认的答案中找到解决办法。跟踪它时会出现一个问题

除非您准备在方法实现中使用,否则我将避免混合泛型类型参数和条件类型:编译器实际上无法验证某个值是否可分配给延迟的条件类型,这取决于某个尚未指定的泛型类型参数。如果你真的想这样做,你可以:

class BaseElementAsssert {
    public static create<T extends typeof BaseElementAsssert>(this: T): InstanceType<T> {
        this.createHelper();
        const r = new this();
        return r as InstanceType<T>; // assert here
    }
    public static createHelper() {
        // implementation omitted.
    }
}
好吧,希望这会有帮助;祝你好运


如果要返回实例,为什么要返回InstanceType?@RobbyCornelissen,我对typescript不熟悉。如果不是,我如何注释返回类型?那么您希望将什么作为参数传递给create函数?一个例子?或者类型?create应该是BaseElement类型的静态函数。在实际代码中,它有其他参数,就像构造函数一样。InstanceType是一种条件类型,编译器无法很好地理解依赖于未指定类型参数的条件类型的可赋值性。考虑签名创建:new = t:t。
class BaseElementAsssert {
    public static create<T extends typeof BaseElementAsssert>(this: T): InstanceType<T> {
        this.createHelper();
        const r = new this();
        return r as InstanceType<T>; // assert here
    }
    public static createHelper() {
        // implementation omitted.
    }
}
class BaseElement {
    public static create<T extends BaseElement>(this: typeof BaseElement & (new () => T)) {
        this.createHelper();
        const r = new this();
        return r;
    }
    public static createHelper() {
        console.log("called createHelper on " + this.name);
    }
}