2

The syntax of the interface has me confused. It looks overloaded but when I try to create a function with either signature the compiler tells me that the other signature is missing. The goal is to mock the function for a Jest unit test.

interface SearchResultSetEachFunction {
  promise(callback: (result: Result) => boolean): Promise<boolean>;
  (callback: (result: Result) => boolean): void;
}

1 Answer 1

2

It's not overloaded, it a function that also has a property named promise. You can use Object.assign to create such an object:


let fn: SearchResultSetEachFunction = Object.assign(function (callback: (result: Result) => boolean): void {

}, {
    promise(callback: (result: Result) => boolean): Promise<boolean> {
      return Promise.resolve(false)
    }
})

Playground Link

Or in newer versions of typescript you can use a function declaration and directly assign the promise member in the same scope as the declaration to have ts recogize it as a new memeber:


function mockSearchResultSetEachFunction(callback: (result: Result) => boolean): void {

}
mockSearchResultSetEachFunction.promise = function (callback: (result: Result) => boolean): Promise<boolean> {
  return Promise.resolve(false)
}

let fn: SearchResultSetEachFunction = mockSearchResultSetEachFunction

Playground Link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.