Dallas
Dallas

Reputation: 928

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?

Upvotes: 1

Views: 122

Answers (1)

popham
popham

Reputation: 592

You're missing a Class<.> wrapper on the argument's type (useIt(TheClass: IClass) should be 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).

Upvotes: 2

Related Questions