我认为这是正确实现泛型的问题,但我不确定。
我在这里创建了一个代表问题的Github要点:https : //gist.github.com/ORESoftware/66b72b4b85262d957cb03ad097e4743e
说我有这个超类:
class A {
foo(): A {
return this;
}
}
和几个子类,例如一个看起来像这样:
class B extends A {
bar(): B {
return this;
}
}
所以如果我这样做
new B().foo().bar()
这将在运行时工作,但不能与TypeScript一起编译。这是因为foo()
将返回类型声明为A
,而不是type B
。
我该如何返回类型this
,而不是声明foo()
始终返回type A
?
我尝试了这个:
但是我得到这个错误:
您必须返回this
使用多态此类型的类型。
abstract class A {
foo(): this {
return this;
}
}
class B extends A {
bar(): this {
return this;
}
}
这将允许
const b = new B();
b.foo().bar();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句