gpt4 book ai didi

typescript - 什么 AsyncGenerator TypeScript 类型会产生 Promise?

转载 作者:行者123 更新时间:2023-12-03 23:35:01 25 4
gpt4 key购买 nike

我正在尝试为下面的函数分配一个返回类型:

async function *sleepyNumbers() {  // what TypeScript type is this?
let n = 0;
while (true) {
yield new Promise(resolve => resolve(n++));
await new Promise(resolve => setTimeout(resolve, 500));
}
}

(async () => {
for await (const i of sleepyNumbers())
console.log(i);
})();


生成器正在生成一个解析为 number 的 Promise。将类型设置为 Promise<number> 失败并显示以下错误消息:

TS2739: Type 'AsyncGenerator' is missing the following properties from type 'Promise': then, catch, [Symbol.toStringTag], finally


Iterable 导致了类似的错误。

我可以将类型设置为 AsyncGenerator 但这还不够具体。此函数的返回类型的正确 TypeScript 语法是什么?

最佳答案

它将是 AsyncGenerator<number, never, void> :
number - next 结果never 返回void - next 没有任何参数

您还需要明确键入一个 promise 解析:
yield new Promise<number>(resolve => resolve(n++));
全部一起:

async function *sleepyNumbers(): AsyncGenerator<number, never, void> {
let n = 0;
while (true) {
yield new Promise<number>(resolve => resolve(n++));
await new Promise(resolve => setTimeout(resolve, 500));
}
}

(async () => {
for await (const i of sleepyNumbers())
console.log(i);
})();

关于typescript - 什么 AsyncGenerator TypeScript 类型会产生 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60681826/

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