microsoft / microsoft/TypeScript

Delegating generator type doesn't align with inferred type of delegated generator

Open
#52,961 0 comments 0 reactions 1 assignee View on GitHub

@rbuckton is already working on this.

Since Feb 28, 2023.

Needs Investigation
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

A delegating generator doesn't acquire the type inferred from the generator it delegates to. This is true even of the simplest delegating generator that serves identical yields and returns the same value.

The example below is functional and transparent to the wrapped generator as expected. However, attempts to explicitly declare the type of the returned generator function using to the inferred Sequence fails. This is true regardless if we add a return type for wrapGeneratorFn or a return type for the delegating generator function created inside wrapGeneratorFn.

function wrapGeneratorFn<Sequence extends Generator>(
  fn: () => Sequence
) /* : () => Sequence */ { // uncomment this typing - errors
  return function* () /* : Sequence */ { // OR uncomment this typing - also errors
    return yield* fn();
  };
}
Workaround - declare Yielded, Returned, Nexted

It seems somehow there is no placeholder for the Yielded, Returned, Nexted bindings that were inherited from Sequence causing them to be implicitly broadened.

A workaround is to introduce explicit bindings for Yielded, Returned and Nexted, but I believe this should not be necessary given that Sequence was inferred directly from the delegated generator, and so the delegating generator CANNOT have any other type than Sequence, so I don't know where the broadening comes from.

function wrapGeneratorFn<Yielded, Returned, Nexted>(
  fn: () => Generator<Yielded, Returned, Nexted>
) {
  return function* () : Generator<Yielded, Returned, Nexted> {
    return yield* fn();
  };
}
🔎 Search Terms

Generator inference delegating

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about generator inference
⏯ Playground Link

Example playground with hard-to-type delegating generator

💻 Code
Typing return type of delegating generator function
function wrapGeneratorFn<Sequence extends Generator>(
  fn: () => Sequence
) {
  return function* () : Sequence { // COMPILER ERROR
    return yield* fn();
  };
}
# Typing return type of wrapGeneratorFn
function wrapGeneratorFn<Sequence extends Generator>(
  fn: () => Sequence
): () => Sequence { // COMPILER ERROR
  return function* () {
    return yield* fn();
  };
}
🙁 Actual behavior

The inferred type Sequence cannot be used in the delegating generator function's type declaration, even though it delegates to a Sequence

🙂 Expected behavior

I would expect the delegating generator to be able to be declared as having a return value of Sequence

Motivating example

I've been experimenting with this pattern to create terse generator functions with associated state but I struggled to type them explicitly without being very verbose. Allowing the type to be inferred without any declaration creates a correct result, but makes it less clear what commitments any function meets, prevents certain patterns which require explicit typing, and violates popular linting rules which expect that all function return types can be explicit. In the more detailed example below the flagGeneratorFn call cannot have its return type populated based on Sequence.


interface Flags {
  active: boolean;
  visited: boolean;
}

function stringifyFlags(flags: Flags) {
  const { active, visited } = flags;
  return JSON.stringify({
    active,
    visited,
  });
}

function flagGeneratorFn<Sequence extends Generator>(
  generatorFn: () => Sequence
) {
  const flaggedFn = Object.assign(
    function* (){
      flaggedFn.active = true;
      flaggedFn.visited = true;
      const returned = yield* generatorFn();
      flaggedFn.active = false;
      return returned;
    },
    {
      active: false,
      visited: false,
    }
  );
  return flaggedFn;
}

/** EXAMPLE USAGE */

const myFn = flagGeneratorFn(function* () {
  yield "one";
  yield "two";
  yield "buckle my shoe";
});

//flags before creating Sequence
console.log(`Sequence not yet created. State: ${stringifyFlags(myFn)}`);

// create sequence
const mySequence = myFn();

// flags during iteration
for (const item of mySequence) {
  console.log(`Sequence yielded ${item}. State: ${stringifyFlags(myFn)}`);
}

// flags at end of sequence
console.log(`Sequence finished: State: ${stringifyFlags(myFn)}`);

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.