-
Notifications
You must be signed in to change notification settings - Fork 12.8k
RHS expression type in assignment incorrectly inferred #3123
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
The current design is that type guards narrow down the known constituent types of a union type, but they don't narrow to anything just based on the instanceof operator. Otherwise there'd be no need to use a union type here at all, you could just type |
I thought that was what my example did, narrow down the constituents of the union type. Here's another example: class Uri {
uriString: String;
}
function repro(uri: String | Uri) {
if (uri instanceof Uri) {
uri = uri.uriString; // error
}
}
function workaround(uri: String | Uri) {
var theUri = uri;
if (theUri instanceof Uri) {
uri = theUri.uriString;
}
} I certainly wouldn't want to type |
I believe the reason you're getting issues in both examples is because type-guards don't narrow variables in scopes where you assign to those variables. |
@DanielRosenwasser, that's what it feels like to me too. It seems to assign one type to the entire code block, in this case the |
Sorry, I misread the original example. @DanielRosenwasser is right, the issue is related to the assignment rule we have for type guards. |
Basically duplicate of #2388, then? |
@RyanCavanaugh, pretty close. Could be used as another test case. |
To completely fix #1587 TypeScript should also support:
Currently it results in
Property 'entries' does not exist on type 'Object | Object[]'
. It seemsmessage
on the RHS switches fromArray
back toObject | Object[]
prematurely.Workaround:
The text was updated successfully, but these errors were encountered: