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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:19:11  来源:igfitidea点击:

How to use generator function in typescript

javascripttypescriptecmascript-6generator

提问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++;
    }   
}

Here is the playground link for the same

这是相同的操场链接

回答by Bergi

The nextmethod 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 窗口以识别更改。