microsoft / microsoft/TypeScript

Type narrowing based on iterator `done` value?

Open
#31,952 0 comments 0 reactions 1 assignee View on GitHub

@rbuckton is already working on this.

Since Jun 26, 2019.

Needs Investigation
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms:

Code

interface MyIterator<T> {
    next():
      | {
          done: false;
          value: T;
        }
      | {
          done: true;
          value: undefined;
        };
    [Symbol.iterator](): MyIterator<T>;
}

interface Item { name: string }

function m(iter: MyIterator<Item>) {
    for (const it of iter) {
        console.log(it.name);           // Error here complaining about 'it': Object is possibly 'undefined'.ts(2532)
    }
}

Expected behavior:

Actual behavior:

Playground Link:
https://typescript-play.js.org/?downlevelIteration=true#code/JYOwLgpgTgZghgYwgAgLIE8CSkpzAeygB4AVAPmQG8AoZO5ECADzAAoBKALlvroB8qPXrwAm+Rp2TwANgGcIAbiHC6ANzjSArhEkklKugF9l-QQfpiJyMFG37zydVp3JNIERBigII+yuO8fsgA2gDK6AC2AEb40gB0wDh4hAC6HJIY2NDJxORKxtSgOPBIyFkRVAxwES6yNqAA5sgFMG4IYMDiyBGsidAZWEkExOVk7Gb0MITIrAjidciJyPgwizjjNOZzILKxEHHS+A29YHEg1RDsCg50APS3yACiUFDTABbQKHMRAA7ScKBGsg4DFNGBkAByRIQyQAeSiACsIO1FrJkD98LJZMAotJ0JC3B4vIwRBC4mBZKwAEwAVgAzFT2NRlMZDEA

Related Issues:
https://github.com/microsoft/TypeScript/issues/11450 seems related. but here even with --strictNullChecks same error is reported here.

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.