typescript 如何在打字稿中使用生成器函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42655512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use generator function in typescript
提问by anandaravindan
I am trying to use generator function in typescript. But the compiler throws error
我正在尝试在打字稿中使用生成器函数。但是编译器抛出错误
error TS2339: Property 'next' does not exist on type
error TS2339: Property 'next' does not exist on type
Below is an closest sample of my code.
下面是我的代码的最接近示例。
export default class GeneratorClass {
constructor() {
this.generator(10);
this.generator.next();
}
*generator(count:number): Iterable<number | undefined> {
while(true)
yield count++;
}
}
回答by Bergi
The next
method exists on the generator that the function returns, not on the generator function itself.
该next
方法存在于函数返回的生成器上,而不是生成器函数本身上。
export default class GeneratorClass {
constructor() {
const iterator = this.generator(10);
iterator.next();
}
*generator(count:number): IterableIterator<number> {
while(true)
yield count++;
}
}
回答by vossad01
I was seeing this error because my tsconfig.jsonwas targeting es5
.
我看到这个错误是因为我的tsconfig.json是针对es5
.
I simply changed (excerpted) from:
我只是从以下内容更改(摘录):
"target": "es5",
"lib": [
"es5",
"es2015.promise"
]
to:
到:
"target": "es6",
"lib": [
"es6"
]
and the error went away.
错误消失了。
Note: For VS Code I needed to reload the window for IntelliSense to recognize the change.
注意:对于 VS Code,我需要重新加载 IntelliSense 窗口以识别更改。