Skip to content

Type erroneously widened for property access after for loop when using comma operator #49111

@dummdidumm

Description

@dummdidumm

Bug Report

This is somewhat a continuation of #41625. I found a case where the control flow breaks when using an if block to narrow a type, using a for loop inside that if block, and then accessing the object which should work due to the if-check, all while using a comma operator.

This may seem like an edge case but we need this in our Svelte->TS transformation for intellisense when using stores (sveltejs/language-tools#1475) Update: We no longer depend on using the comma operator, so this issue isn't high priority for us anymore.

🔎 Search Terms

comma operator for loop type narrowing

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing

⏯ Playground Link

Playground link with relevant code

💻 Code

let foo = () => {};
let bar: { a?: { b?: string } } = null as any;

if ((foo(), bar)?.a?.b) {
	(foo(), bar).a.b; // access works
	for (const a of []) {
	}
	(foo(), bar).a.b; // access fails, should work
}

🙁 Actual behavior

Property access after for loop fails with a "could be undefined" type error.

🙂 Expected behavior

Control flow isn't affected by for loop.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: Control FlowThe issue relates to control flow analysis

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions