HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptCriticalCanonical

How to define the type of an async function?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfunctionthedefinetypeasync

Problem

I tried to define a type of async function, but failed in compilation, see below:

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:

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.