Search code examples
typescripttypescript3.0

How to use yield in Typescript classes


I am fresher to Typescript, while learning from the site, I got to know that yield can be used for Asynchronous Iteration using for-await-of. The below is the function in Javascript. Please help me how to use in Typescript classes. When I write the below code, I get the error as TS1163: A 'yield' expression is only allowed in a generator body. I want to write the below code in Typescript class.

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();

I also tried to write in a Typescript class, but it gives compilation issue.

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

Solution

  • You need to put the token * in front of your method:

    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;
                }
            }
        }
    }
    

    Playground Link