在打字稿中,如何定义异步函数的类型 [英] In typescript, how to define type of async function

查看:30
本文介绍了在打字稿中,如何定义异步函数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试定义一种异步函数,但是编译失败,见下图:

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<string> {
        await this.Fn("fds") // complain here: cannot invoke an expression whose type lacks a call signature
        return ''
    }
}

谁能帮我解决这个问题?

Can anyone help me work this out?

推荐答案

发现这个搜索如何为异步箭头函数声明typedef".

Found this searching how to declare a "typedef" for an async arrow function.

如果你只是将函数的返回类型声明为 Promise 就可以了:

It works if you just declare the return type of the function to be a Promise:

interface SearchFn {
    (subString: string): Promise<boolean>;
}

或作为类型声明:

type SearchFn = (subString: string) => Promise<boolean>;

Microsoft 的 TS Linter 将推荐第二种语法.

Microsoft's TS Linter will recommend this second syntax.

这篇关于在打字稿中,如何定义异步函数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆