简体   繁体   English

如何定义采用在流中实现接口的Class的函数?

[英]How to define function that takes a Class that implements interface in flow?

Example: 例:

interface IClass {
  test(arg: String): Promise<*>
}

class MyClass implements IClass {
  async test(arg) { await dosomething(arg) }
}

async function useIt(TheClass: IClass) {
  const obj = new TheClass()
  obj.test('arg')
}

However, this results in: 但是,这导致:

const obj = new TheClass()
            ^^^^^^^^^^^^ constructor call. Constructor cannot be called on
const obj = new TheClass()
                ^^^^^^^^ IClass

Which, I understand, as IClass is the interface, but how would one go about specifying a "class" that implements a specific "interface" as a parameter to a function? 我知道,哪一个是IClass接口,但是如何指定一个实现特定“接口”的“类”作为函数的参数呢?

You're missing a Class<.> wrapper on the argument's type ( useIt(TheClass: IClass) should be useIt(TheClass: Class<IClass>) ). 您缺少参数类型的Class<.>包装器( useIt(TheClass: IClass)应该是useIt(TheClass: Class<IClass>) )。 That, and interfaces don't assume a default constructor, so you'll need an explicit one on IClass (with return type void ). 而且,接口不采用默认构造函数,因此您需要在IClass上使用显式构造函数(返回类型为void )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM