【发布时间】: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