-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue
Milestone
Description
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
AIVASteph
Metadata
Metadata
Assignees
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue