
[英]Can TypeScript return the subclass if a function has the superclass as its return type?
[英]Is there a generics notation so a TypeScript superclass method can return a subclass-compatible type?
这是我正在谈论的那种情况:
class Foo {
constructor(public n: number) {}
get value(): number { return this.n; }
addTwo(): Foo {
this.n += 2;
return this;
}
}
class Bar extends Foo {
// Can I avoid the code below, and type addTwo() in a way
// that returns type Bar for a Bar instance?
//
// addTwo(): Bar {
// return super.addTwo() as Bar;
// }
addThree(): Bar {
this.n += 3;
return this;
}
}
const baz: Bar = new Bar(7).addTwo().addThree();
对于最后一行,我收到此错误:
我找不到任何类型的符号来指代完成这项工作的this
类型。 当访问该方法的实例本身是Bar
类型时,我希望addTwo()
方法被视为返回类型Bar
。
请参阅多态这种类型
这种类型的多态表示一种类型,它是包含 class 或接口的子类型。 这就是所谓的 F 有界多态性,很多人都知道它是流畅的 API 模式。 例如,这使得层次流畅的接口更容易表达。
class Foo {
constructor(public n: number) {}
get value(): number { return this.n; }
addTwo(): this {
this.n += 2;
return this;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.