【问题标题】:How to access IteratorResult value?如何访问 IteratorResult 值?
【发布时间】:2021-07-26 11:50:10
【问题描述】:

我是 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函数返回的?

【问题讨论】:

    标签: typescript generator


    【解决方案1】:

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

    底线,当你调用生成器的next 时,函数暂停并返回yield 关键字上的任何内容,并在我们再次调用next 时再次恢复,只是在下一个yield 上暂停直到函数最终返回。

    在你的情况下,

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

    你有两个停止点,一个是函数在第 2 行产生并返回函数,下一个函数的自然返回是 void。因此,您的函数可能返回函数或 void,因此您正确指出的返回类型是:

    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)
    

    TS Playground 链接:https://tsplay.dev/mL9VbW

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 2023-03-28
      • 2016-04-18
      • 2018-10-13
      • 2020-09-24
      相关资源
      最近更新 更多