gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:54:31 24 4
gpt4 key购买 nike

我想编写一个接口(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com