ES6 generators

TypeScript 1.6 adds support for generators when targeting ES6.

A generator function can have a return type annotation, just like a function. The annotation represents the type of the generator returned by the function. Here is an example:

  1. function *g(): Iterable<string> {
  2. for (var i = 0; i < 100; i++) {
  3. yield ""; // string is assignable to string
  4. }
  5. yield * otherStringGenerator(); // otherStringGenerator must be iterable and element type assignable to string
  6. }

A generator function with no type annotation can have the type annotation inferred. So in the following case, the type will be inferred from the yield statements:

  1. function *g() {
  2. for (var i = 0; i < 100; i++) {
  3. yield ""; // infer string
  4. }
  5. yield * otherStringGenerator(); // infer element type of otherStringGenerator
  6. }