javascript - 如何使用采用接口(interface)实现类作为参数的方法编写 Flow 接口(interface)?

标签 javascript abstract-class flowtype

我想编写一个接口(interface),定义一个方法,该方法采用实现此接口(interface)的类的实例作为参数或返回类型。

也就是说,我希望编译器知道它可以调用该类的接口(interface)方法和任何其他方法。我的直觉是尝试这个:

interface Doable {
  doSomething(otherThing: Doable): Doable
  interfaceMethod(): boolean
}

class Foo implements Doable {
  doSomething(otherFoo: Foo): Foo {
    if (this.interfaceMethod() && this.nonInterfaceMethod()) {
      return otherFoo;
    } else {
      return this;
    }
  }
  interfaceMethod(): boolean {
    return true;
  }
  nonInterfaceMethod(): boolean {
    return true;
  }
}

但是,Flow 并不认为 FoodoSomething 方法有效,因为它表示 FooDoable 不兼容.

可以这样使用接口(interface)吗?除了在接口(interface)方法参数类型上使用 any 之外,还有其他方法可以做到这一点吗?

最佳答案

您可以给Doable接口(interface)代表其确切子类型的类型参数:

interface Doable<A> {
  doSomething(otherThing: A): A,
  interfaceMethod(): boolean,
}

class Foo implements Doable<Foo> {...}

这个类型参数,以及我们实现的方式Doable<Foo> ,让类型检查器跟踪 doSomething 中的确切实现类型方法。

关于javascript - 如何使用采用接口(interface)实现类作为参数的方法编写 Flow 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47682619/

相关文章:

Javascript 构造函数似乎正在丢失数据

javascript - 使用 Axios 等待服务器响应的时间

javascript - 如何从引导箱内的通配符 id onclick 事件?

c++ - 在 C++ 中初始化抽象基类的子类数组

flowtype - "exponentially large number of cases"最新流中的错误,具有常见的传播模式

javascript - 通过 JavaScript 控制嵌入视频

java - 在 Java 的父类(super class)构造函数中调用抽象方法

.net - 将WCF与抽象类一起使用

dom - 将流与 document.querySelector 一起使用

flowtype - npm 模块如何开箱即用地提供自己的 Flow libdef?