简体   繁体   English

如何在打字稿中使用生成器功能

[英]How to use generator function in typescript

I am trying to use generator function in typescript.我正在尝试在打字稿中使用生成器功能。 But the compiler throws error但是编译器会抛出错误

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 这是相同的游乐场链接

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

I was seeing this error because my tsconfig.json was 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 窗口以识别更改。

To solve the problem, it is very important to know the differences between generator functions (generators for short) and their return values.要解决这个问题,了解生成器函数(简称生成器)及其返回值的区别非常重要。

A generator function (marked by the asterisk) is a function, which returns a generator object.生成器函数(用星号标记)是一个返回生成器对象的函数。 The generator object fulfills the requirements of an iterator and an iterable .生成器对象满足迭代器可迭代对象的要求。

Iterators have a next method (that's the method you are looking for in your question).迭代器有一个next方法(这是您在问题中寻找的方法)。 And iterables have a property called Symbol.iterator (specifying a default iterator), which makes them usable in for-loops.可迭代对象有一个名为Symbol.iterator的属性(指定一个默认迭代器),这使得它们可以在 for 循环中使用。

Because a generator function returns a generator object and a generator object is an iterable iterator, you have to declare a return type of IterableIterator .因为生成器函数返回一个生成器对象,而生成器对象是一个可迭代的迭代器,所以你必须声明一个IterableIterator的返回类型。 In your case it will be IterableIterator<number> .在您的情况下,它将是IterableIterator<number>

Because the terms here are confusingly similar, I have recorded a Generator tutorial which explains the differences.因为这里的术语非常相似,所以我录制了一个解释差异的生成器教程 Make sure to set your target to es6 in your tsconfig.json , when using generator functions.确保您的设定targetes6tsconfig.json ,使用发电机的功能时。

在此处输入图片说明

Here is another example which uses the Generator type of typescript.这是另一个使用 Generator 类型的打字稿的示例。 Some of the types at the assignment of iterators eg const iterator: Generator<number> can be omitted since TS can infer them.分配迭代器时的某些类型,例如const iterator: Generator<number>可以省略,因为 TS 可以推断它们。 However I included them in this example to be more explicit.但是,为了更加明确,我将它们包含在此示例中。

class GeneratorClass {
    *generator(count:number): Generator<number> {
        while(count < 3)
            yield count++;
    }   
}

const generatorObject = new GeneratorClass();

// Getting our generator object which we can use as an iterator.
const iterator: Generator<number> = generatorObject.generator(1);


console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
/*
[LOG]: {
  "value": 1,
  "done": false
} 
[LOG]: {
  "value": 2,
  "done": false
} 
[LOG]: {
  "value": undefined,
  "done": true
} 
*/

// Alternative more clean for of syntax. 
// For of can iterate over any iterable
// Can be used since every Generator is an Iterator
const iterator2: Generator<number> = generatorObject.generator(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在生成器 function 中使用 while 循环 - how to use while loop in generator function 如何在TypeScript中使用函数类型 - How to use Function types in TypeScript 正确键入在 TypeScript 中调用另一个生成器 function 的生成器 function - Properly typing a generator function that calls another generator function in TypeScript 如何在打字稿中注释生成器函数 - How to annotate generator functions in typescript 有没有办法将回调 function 转换为 TypeScript/JavaScript 中的生成器? - Is there a way to convert a callback function into a generator in TypeScript/JavaScript? 如何将生成器函数用作fetch调用返回的promise中的回调? - How to use a generator function as a callback inside a promise returned by fetch call? 如何在生成器 function 中使用 Promise 和 setTimeout 来创建异步生成器? - How to use Promise and setTimeout within a generator function in order to create an async generator? 如何将 TypeScript 定义文件用于另一个 function - How to use a TypeScript definition file for another function 如何使用 reselect createStructuredSelector function 和 typescript? - How to use reselect createStructuredSelector function with typescript? 如何为 map function 正确使用 TypeScript? - How to use TypeScript correctly for map function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM