如何在 Typescript 中使用 yield 类
How to use yield in Typescript classes
我对 Typescript 比较陌生,在从网站上学习时,我了解到 yield 可以用于使用 for-await-of 的异步迭代。下面是Javascript中的函数。请帮助我如何在 Typescript classes 中使用。当我写下面的代码时,我得到错误 TS1163: A 'yield' expression is only allowed in a generator body. 我想写下面的打字稿中的代码 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();
我也试过用 Typescript 写 class,但它给出了编译问题。
public getValues(): number {
let index = 1;
while(true) {
yield index;
index = index + 1;
if (index > 10) {
break;
}
}
}
你需要在你的方法前面加上标记*
:
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;
}
}
}
}
我对 Typescript 比较陌生,在从网站上学习时,我了解到 yield 可以用于使用 for-await-of 的异步迭代。下面是Javascript中的函数。请帮助我如何在 Typescript classes 中使用。当我写下面的代码时,我得到错误 TS1163: A 'yield' expression is only allowed in a generator body. 我想写下面的打字稿中的代码 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();
我也试过用 Typescript 写 class,但它给出了编译问题。
public getValues(): number {
let index = 1;
while(true) {
yield index;
index = index + 1;
if (index > 10) {
break;
}
}
}
你需要在你的方法前面加上标记*
:
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;
}
}
}
}