snippettypescriptCriticalCanonical
How to define the type of an async function?
Viewed 0 times
howfunctionthedefinetypeasync
Problem
I tried to define a type of async function, but failed in compilation, see below:
Can anyone help me work this out?
interface SearchFn {
async (subString: string): string;
}
class A {
private Fn: SearchFn
public async do():Promise {
await this.Fn("fds") // complain here: cannot invoke an expression whose type lacks a call signature
return ''
}
}Can anyone help me work this out?
Solution
It works if you just declare the return type of the function to be a Promise:
or as a type declaration:
Microsoft's TS Linter will recommend this second syntax.
interface SearchFn {
(subString: string): Promise;
}or as a type declaration:
type SearchFn = (subString: string) => Promise;Microsoft's TS Linter will recommend this second syntax.
Code Snippets
interface SearchFn {
(subString: string): Promise<boolean>;
}type SearchFn = (subString: string) => Promise<boolean>;Context
Stack Overflow Q#38744159, score: 427
Revisions (0)
No revisions yet.