In typescript, how to define type of async function
Found this searching how to declare a "typedef" for an async arrow function.
It works if you just declare the return type of the function to be a Promise:
interface SearchFn {
(subString: string): Promise<boolean>;
}
or as a type declaration:
type SearchFn = (subString: string) => Promise<boolean>;
Microsoft's TS Linter will recommend this second syntax.
The async
keyword is used to indicate to the compiler/runtime that the function in question will use await
internally (so it can put in the required scaffolding to enable it).
This means that async
only has meaning for the implementation of the function, not it's interface. Therefore having async
on an interface's method isn't useful, you want to say that the function returns a certain Promise
(in your case Promise<string>
) but you don't want to enforce that the interface's implementer implements this in a certain way (using await
).
So as other said before me:
interface SearchFn {
(subString: string): Promise<string>;
}
Then, whoever chooses to implement this function can choose to use async
, plain old Promise.then
or perhaps even some new methodology that will come up in the future.