简体   繁体   中英

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

You need to put the token * in from of you 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM