Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
            }
        }
    }
like image 272
Deba Avatar asked Mar 09 '26 09:03

Deba


1 Answers

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

like image 162
Titian Cernicova-Dragomir Avatar answered Mar 12 '26 05:03

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!