如何访问 IteratorResult 值?

How to access IteratorResult value?

我是 TypeScript 的新手,很难解决问题。

假设我有一个函数可以生成如下所示的另一个函数。

function sayHello() {
    return {
        name: 'mike'
    }
};
function* test() {
    yield(sayHello);
}

我试图在测试中访问 name 属性,但收到以下错误消息。

Property 'name' does not exist on type 'void | (() => { name: string; })'. Property 'name' does not exist on type 'void'.

这是我的测试代码

const a = test();
a.next().value.name

有没有办法表明 value 对象是从 sayHello 函数返回的?

您面临的问题是 yield 的工作方式。这是 MDN doc 的一个很好的例子。

最重要的是,当您调用生成器的 next 时,函数会暂停并 returns yield 关键字上的任何内容,并在我们调用 [=15] 时再次恢复=] 再次,只是在下一个 yield 上暂停,直到函数 return 最终结束。

在你的情况下,

function* test() {
    yield(sayHello);
}

您有两个停靠点,一个是函数在第 2 行让步并且 return 是函数,下一个是函数的自然 return,即 void。因此,您的函数可能 return 函数或 void,因此您正确指出的 return 类型是:

void | (() => { name: string; })

让我们用这些信息看看问题所在。当你说,

const a = test();
const value = a.next().value

Typescript 无法保证 value 是函数还是 void,因为它不跟踪 next() 被调用的次数以及哪个 next() 会导致函数,哪个会导致 void.所以,责任在开发者身上。

这就是你的做法:

function sayHello() {
    return {
        name: 'mike'
    }
};
function* test() {
    yield(sayHello);
}

const a = test();
const v = a.next().value;

// We need to ensure that this v is not void, 
// which leaves it being the function
if(v){
  const r = v().name;
  console.log(r) // works!
}

// Now that it has yielded, this would be undefined
console.log(a.next().value)

Link 到 TS 游乐场:https://tsplay.dev/mL9VbW