考虑这样一种情况,您有一个从类 A 扩展的类 B。您创建一个类型 B 的对象并调用 A 中定义的方法 fooA,然后调用 B 中定义的方法 fooB。
class A {
fooA () {
console.log('fooA called')
return this
}
}
class B extends A {
fooB () {
console.log('fooB called')
return this
}
}
new B().fooA().fooB()
运行时,代码按预期记录以下内容
fooA called
fooB called
因此 Javascript 理解 new B().fooA()
是 B 类的对象。但是 Flow 给我以下错误消息:
Cannot call new B().fooA().fooB because property fooB is missing in A
要做什么?我对不需要更改父类 A 的解决方案感兴趣,因为它是在 npm 包中定义的。不过我可以改变 B。
最佳答案
如果您将 fooA
方法键入为返回 this
,那么 Flow 会理解任何扩展 A
类的类也将返回一个实例他们自己来自方法:
( Try )
class A {
fooA (): this {
console.log('fooA called')
return this
}
}
class B extends A {
fooB () {
console.log('fooB called')
return this
}
}
new B().fooA().fooB() // No error
由于您不想更改 A
类:另一种实现此功能的简单方法是键入 B
的 fooA
函数> 返回 B
实例的类:
( Try )
class A {
fooA () {
console.log('fooA called')
return this
}
}
class B extends A {
fooB () {
console.log('fooB called')
return this
}
fooA: () => B; // Hey Flow, this actually returns a B
}
new B().fooA().fooB() // No error!
关于javascript - JS 流 : Is inheritance in Flow broken?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50242813/