【问题标题】:In typescript, how to define type of async function在打字稿中,如何定义异步函数的类型
【发布时间】:2022-03-02 23:14:23
【问题描述】:

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

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 ''
    }
}

谁能帮我解决这个问题?

【问题讨论】:

  • Promise 不起作用?
  • 请说明您定义Fn的方式/位置。

标签: typescript


【解决方案1】:

发现这个搜索如何为异步箭头函数声明“typedef”。

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

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

或作为类型声明:

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

Microsoft 的 TS Linter 会推荐第二种语法。

【讨论】:

  • 聪明,谢谢,async func其实是一个Promise返回函数。
  • @Ron 值得一提的是,这是不正确的,async 函数只是使用 await。查看 Motti 的回答
  • 人们应该注意,返回 promise 的函数不一定是异步函数。
  • 如果没有返回值怎么办? ): Promise&lt;undefined&gt; 对我来说失败了。我只需要一个异步函数,这样我就可以在其中使用await...
  • @dcsan 承诺
【解决方案2】:

async 关键字用于向编译器/运行时指示相关函数将在内部使用await(因此它可以放入所需的scaffolding to enable it)。

这意味着async只对函数的实现有意义,而不是接口。因此,在接口的方法上使用async 没有用,您想说该函数返回某个Promise(在您的情况下为Promise&lt;string&gt;),但您不想强制接口的实现者在某种方式(使用await)。

正如其他人在我之前所说的那样:

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

然后,选择实现此功能的任何人都可以选择使用async、普通的旧Promise.then,或者甚至可能是将来会出现的一些新方法。

【讨论】:

  • 很好的答案,并简洁地解释了“为什么”。
【解决方案3】:

将返回对象的类型传递给 Promise 泛型。

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

您也可以声明一个AsyncFunction 泛型类型。

type AsyncFunction <A,O> = (...args:A) => Promise<O> 
type SearchFn = AsyncFunction<[string], string>

AsyncFunction 是一个泛型类型,它接收两个类型变量 - 输入 (A) 的类型和输出的类型。

【讨论】:

    猜你喜欢
    • 2023-02-14
    • 2021-06-17
    • 2021-12-15
    • 1970-01-01
    • 2019-12-25
    • 2018-05-03
    • 1970-01-01
    • 2018-12-27
    • 2023-01-19
    相关资源
    最近更新 更多