gpt4 book ai didi

javascript - typescript 符号异步函数作为类型/接口(interface)属性

转载 作者:搜寻专家 更新时间:2023-10-30 22:05:43 25 4
gpt4 key购买 nike

我在使用异步(箭头)函数作为类型/接口(interface)属性的语法时遇到了问题。我已经做了一些研究,但除了这个 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 转译器说它找不到名称“async”。如何判断 MyType 中的函数“funct”是异步的?我需要在其中使用等待...

最佳答案

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

您真正想要的是告诉编译器该函数不返回string[]。而是一个Promise<string[]> .这意味着调用者无法直接访问结果,但需要使用 then在返回的 promise 或使用await得到结果。

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

关于javascript - typescript 符号异步函数作为类型/接口(interface)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54382623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com