Skip to content

Generator<T, TReturn>['next'] doesn't narrow properly when using assignment expressions or the comma operator #35484

Closed
@JakeTunaley

Description

@JakeTunaley

TypeScript Version: 3.8.0-dev.20191203

Search Terms:

  • generator
  • generators
  • iterator
  • iterators
  • narrow
  • narrowing
  • assignment
  • expression
  • next
  • comma
  • operator

Code

function* generator () {
	yield 4;
	return 'hello world';
}

function consumer1 () {
	const gen = generator();
	let result = gen.next();
	while (!result.done) {
		((x: number) => {})(result.value);
		result = gen.next();
	}
	((x: string) => {})(result.value);
}

function consumer2 () {
	const gen = generator();
	let result;
	while (!(result = gen.next()).done) {
		((x: number) => {})(result.value);
	}
	((x: string) => {})(result.value);
}

function consumer3 () {
	const gen = generator();
	let result;
	while (result = gen.next(), !result.done) {
		((x: number) => {})(result.value);
	}
	((x: string) => {})(result.value);
}

Expected behavior:

Type narrowing for result.value should be the same in consumer1, consumer2, and consumer3.

Actual behavior:

consumer1 narrows result.value.

consumer2 and consumer3 don't narrow result.value, thus giving the following errors:

Argument of type 'string | number' is not assignable to parameter of type 'number'.

Type 'string' is not assignable to type 'number' .ts(2345)

Argument of type 'string | number' is not assignable to parameter of type 'string'.

Type 'number' is not assignable to type 'string'. ts(2345)

Explicitly declaring the type of result to be IteratorResult<number, string> (the type inferred in consumer1) does not fix the issue.

Playground Link:

Playground Link

Related Issues:

None

Metadata

Metadata

Assignees

Labels

Fix AvailableA PR has been opened for this issueNeeds InvestigationThis issue needs a team member to investigate its status.RescheduledThis issue was previously scheduled to an earlier milestone

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions