Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
yftachman opened this issue Feb 10, 2020 · 0 comments · Fixed by #37134
Closed

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

yftachman opened this issue Feb 10, 2020 · 0 comments · Fixed by #37134
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@yftachman
Copy link

yftachman commented Feb 10, 2020

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
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants