Skip to content

Type narrowing (null check) doesn't work if before instanceof #36709

Closed

Description

@yftachman

TypeScript Version: 3.7.5 && 3.8.0-beta

Search Terms: instanceof, null check, type narrowing

Code

class A {
  constructor(public stringOrUndefined: string | undefined) {

  }
}
class B {
  constructor(public str: string) {

  }
}

const a = new A("123");

// Compiles
if (a.stringOrUndefined) {
  new B(a.stringOrUndefined);
}

// Doesn't compile
if (a.stringOrUndefined && a instanceof A) {
  new B(a.stringOrUndefined)
}

Expected behavior:
If i check an inner property undefined and then verify the type, i would expect typescript to know it is already not undefnied
Actual behavior:
instanceof "resets" the null

Playground Link:
Playground Link

Related Issues:
N\A

Notes
This is a bigger problem if my null check is not on the same if as the instance of, for example:

if (a.stringOrUndefined) {
  if (a instanceof A) {
    new B(a.stringOrUndefined)
  } else {
    // Other code that also involves a.stringOrUndefined
  }
}

As here I cannot reorder the ifs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugFix Available

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions