【问题标题】:Typescript notation async function as type/interface attribute打字稿符号异步函数作为类型/接口属性
【发布时间】:2019-06-20 07:29:45
【问题描述】:

我在将异步(箭头)函数用作类型/接口属性的语法上遇到问题。 我已经做了一些研究,但除了这个https://github.com/Microsoft/TypeScript/issues/22035之外没有发现太多 这对我的情况不是 100% 准确,但总比没有好。而且还是不适合我...

这是关于我在声明中的代码(简化):

export type MyType = {
    att1: string;
    funct: async (param1: string, param2: string) => Promise<string[]>;
};

我在哪里使用它(例如,不是我的实际代码):

import { MyType } from "./MyType";

const myObject: MyType = {
    att1: "First attribute";
    funct: async (param1: string, param2: string): Promise<string[]> => {
        // Code below is an example, in my case it's a database querying
        // But anyway, it's something async
        return new Promise((resolve, reject): void => {
            setTimeout((): void => {
                resolve(["string1", "string2"]);
            }, 5000);
        });
    };
};

TypeScript 转译器说它找不到名称“异步”。 如何判断 MyType 中的函数“funct”是异步的?我需要在其中使用 await...

【问题讨论】:

    标签: javascript node.js typescript typescript-typings


    【解决方案1】:

    答案很简单,你不要告诉编译器函数在界面上是asyncasync 是一个实现细节,它允许您在函数体内使用await。接口的用户并不关心你如何实现你的函数,只关心它返回什么以及需要传入什么参数。

    您真正想要的是告诉编译器该函数不返回string[],而是返回Promise&lt;string[]&gt;。这意味着调用者无法直接访问结果,但需要在返回的 Promise 上使用 then 或使用 await 来获取结果。

    export type MyType = {
        att1: string;
        funct:  (param1: string, param2: string) => Promise<string[]>;
    };
    

    【讨论】:

    • 类型定义中的返回类型是我忘记改的……我只是不知道你不用在接口里加async关键字。无论如何,非常感谢。
    • 如果我想强制函数异步怎么办。我明确希望界面的用户将该方法设为异步方法?
    • @MikeMajara 无法强制执行此操作。从消费者的角度来看,确实没有办法区分异步方法和返回承诺的方法。
    • 如何创建一个实现该接口并具有异步方法的类?
    猜你喜欢
    • 2021-11-13
    • 2023-02-14
    • 1970-01-01
    • 2017-09-16
    • 2021-06-17
    • 2017-05-29
    • 2018-07-14
    • 2020-03-19
    • 2022-01-04
    相关资源
    最近更新 更多