Skip to content

if statement in loop changes type of variable outside the if #19955

Closed

Description

TypeScript Version: 2.7.0-dev.20171112

Code

type U = { kind: "A", xs?: number[] } | { kind: "B", xs?: number[] };
function f(u: U) {
	if (u.xs) {
		for (const b of u.xs) {
			if (u.kind === "A") {}
		}
	}
}

Expected behavior:

No error.

Actual behavior:

src/a.ts(4,19): error TS2532: Object is possibly 'undefined'.

Activity

  1. ghost added
    Bug
    on Nov 13, 2017
  2. ahejlsberg commented on Nov 13, 2017

    @ahejlsberg
    Member

    Duplicate of #18840.

  3. added
    Duplicate
    and removed
    Bug
    on Nov 13, 2017
  4. ahejlsberg commented on Nov 13, 2017

    @ahejlsberg
    Member

    Actually, I'll flip it back to a bug since it is not exactly the same as #18840. However the root cause is similar: A narrowing by a discriminant property (such as u.kind === "A") resets any previous narrowing in effect for the variable. Here, the back edge of the for loop causes the narrowing of u.xs to disappear. This is unfortunately not a simple thing to fix.

  5. added
    Bug
    and removed
    Duplicate
    on Nov 13, 2017
  6. jack-williams commented on Sep 24, 2019

    @jack-williams
    Collaborator

    This looks to be fixed by #32695; specifically, the cases involving loops.

  7. sandersn commented on Oct 1, 2019

    @sandersn
    Member

    Indeed it is. Thanks for noticing!

  8. added
    Fixed
    on Oct 2, 2019
  9. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugFixed

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions