【问题标题】:Return type of this for inherited TypeScript classes not working继承的 TypeScript 类的返回类型不起作用
【发布时间】:2020-07-23 19:54:19
【问题描述】:

我正在尝试创建一个基类,其中继承类必须实现一个返回与自身相同类型的对象的方法。

abstract class Base {
  abstract clone(): this;
}

class Impl extends Base {
  clone(): this {
    return new Impl();
  }
}

很遗憾,我收到了这个错误。

类型“Impl”不可分配给类型“this”。 “Impl”可分配给“this”类型的约束,但“this”可以用约束“Impl”的不同子类型实例化。(2322)

我可以通过施法来解决这个问题:

abstract class Base {
  abstract clone(): this;
}

class Impl extends Base {
  clone(): this {
    return new Impl() as this;
  }
}

...但我不明白为什么这是必要的。为什么new Impl() 不是this 类型?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    错误表明,如果您将 Impl 子类化,则生成的子类型的函数 clone() 将不适合定义的约束。

    class Impl2 extends Impls {
    }
    
    const impl2 = new Impl2();
    impl2.clone(); // method would return Impl type, instead of Impl2 type, so `this` is not correct constraint.
    

    目前,虽然有一种解决方法可以防止通过使用private contructor()Impl 类进一步继承,但编译器/语言服务仍会报告错误,因为无法将类标记为sealed /final.

    【讨论】:

    • 哦,谢谢,现在更清楚了。而且由于 TypeScript 不能让你做一个最终的类,我想没有办法绕过强制转换,是吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多