'instanceof' changes type outside of 'if' statement
See original GitHub issueTypeScript Version: 3.4.*
Search Terms:
instanceof
Code
// @strictNullChecks: true
interface OnChanges {
onChanges(changes: Record<string, unknown>): void
}
interface Validator {
validate(): null | Record<string, unknown>;
}
class C {
validate() {
return {}
}
}
function foo() {
let v: Validator & Partial<OnChanges> = null as any;
if (v instanceof C) {
}
if (v.onChanges) { // error here
v.onChanges({});
}
}
Expected behavior:
No error.
Actual behavior:
Property 'onChanges' does not exist on type 'C | (Validator & Partial<OnChanges>)'.
Property 'onChanges' does not exist on type 'C'.
instanceof
shouldn’t change the type of the variable outside of the if
statement.
This only happens with strictNullChecks
enabled.
Related Issues:
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (3 by maintainers)
Top Results From Across the Web
Java - alternative to many else if statements with instanceof ...
Firstly, I would have them implementing a common interface or superclass. This is so you don't need to test what type of class...
Read more >3 Pattern Matching for the instanceof Operator
Pattern matching involves testing whether an object has a particular structure, then extracting data from that object if there's a match.
Read more >Java “instanceOf”: Why And How To Avoid It In Code - Armedia
It is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we...
Read more >instanceof - JavaScript - MDN Web Docs
The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object.
Read more >Semantics - The Apache Groovy programming language
If left out, the type name will be deemed to refer to an existing variable (presumably ... Despite not changing the semantics of...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
The correct fix is to make an intersection even if one of
type
orcandidate
is assignable to the other - unions only do subtype reduction, so anything that narrows to a type by assignability (rather thansubtype
) will have this issue.This fix was reverted with https://github.com/microsoft/TypeScript/pull/41849