-
Notifications
You must be signed in to change notification settings - Fork 12.8k
'instanceof' changes type outside of 'if' statement #31155
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
Comments
Related to #30461. The underlying issue here is that when narrowing using When combining the narrowing's at Instead of narrowing directly to // If the candidate type is a subtype of the target type, narrow to the candidate type.
// Otherwise, if the target type is assignable to the candidate type, keep the target type.
// Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
// type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
// two types.
return isTypeSubtypeOf(candidate, type) ? candidate :
isTypeAssignableTo(type, candidate) ? type :
isTypeAssignableTo(candidate, type) ? candidate :
getIntersectionType([type, candidate]); I'm not quite sure what the correct fix is here. A heuristic is that when |
The correct fix is to make an intersection even if one of |
Want me to submit a PR removing the assignable cases? |
A similar thing happens with This will run without any errors if (typeof response === 'string' && CANCEL_OPTIONS.includes(response.toLowerCase())) {} This throws an error const isString = typeof response === 'string';
if (isString && CANCEL_OPTIONS.includes(response.toLowerCase())) {} |
This last example is a bit different @Skillz4Killz - you're not narrowing the scope of the variables in the context of that if statement, it's just checking a boolean and TypeScript can't infer that a union has been reduced. @jack-williams - I think a PR sounds great, if not I'll take a look a this next week 👍 |
This fix was reverted with #41849 |
TypeScript Version: 3.4.*
Search Terms:
instanceof
Code
Expected behavior:
No error.
Actual behavior:
instanceof
shouldn't change the type of the variable outside of theif
statement.This only happens with
strictNullChecks
enabled.Playground Link: https://typescript-play.js.org/#code/JYOwLgpgTgZghgYwgAgPIgMIAs4gOYQDOyA3gFDKXID2mO+RAFAvQYQFzIBKEC1UAEwA8hMFFB4ANMgCuIANYhqAdxAA+AJScAbtWACyAXzKhIsRCgBqcADb64YfqQpVtt+5EZbkIGTZvIAD7cvPzCouL40nKKKuoA3EZkZAg2cITEGM5UyG52Ag4QXtk5VFAQYDJQIKTGOcbGMHIIYMC0yDDU1MXkOTYVuZzW+Q5OAGTIAApwUK22QujYuGxqyAC8Pn4B6ci4AJ6JOcAwyIzayKCiuEjUJxgaJZR1VMen2gB0tEsMhA+9pZQPl9WEwSIYNIcqA0gA
Related Issues:
The text was updated successfully, but these errors were encountered: