如何在 Typescript 类中使用 Yield

Deb*_*eba 9 typescript typescript3.0

我对 Typescript 比较陌生,在从该网站学习时,我了解到,yield 可以用于使用 for-await-of 进行异步迭代。下面是 Javascript 中的函数。请帮助我如何在 Typescript 类中使用。当我编写以下代码时,出现错误TS1163:“yield”表达式仅允许在生成器主体中使用。 我想在 Typescript 类中编写以下代码

https://blog.bitsrc.io/keep-your-promises-in-typescript-using-async-await-7bdc57041308

function* numbers() {
  let index = 1;
  while(true) {
    yield index;
    index = index + 1;
    if (index > 10) {
      break;
    }
  }
}

function gilad() {
  for (const num of numbers()) {
    console.log(num);
  }
}
gilad();
Run Code Online (Sandbox Code Playgroud)

我也尝试在 Typescript 类中编写,但它给出了编译问题。

public getValues(): number {
        let index = 1;
        while(true) {
            yield index;
            index = index + 1;
            if (index > 10) {
                break;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 14

您需要将令牌放在*方法前面:

class X {
  public *getValues() { // you can put the return type Generator<number>, but it is ot necessary as ts will infer 
        let index = 1;
        while(true) {
            yield index;
            index = index + 1;
            if (index > 10) {
                break;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

游乐场链接