-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Union Types lead to TypeError #29508
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
I'm not 100% sure this is a bug - the compiler knows If there's a bug at all, it's that |
I don't think this is a bug.
Here, you're only admit that because Maybe this is more what you want to achieve: function isC(obj: ABC): obj is C {
return "c" in test && "foo" in test;
}
if (isC(test)) {
console.log(test.foo.blabla);
} else {
console.log('Safe passed.');
} Also, if |
For the record, even if it's not a bug, I can see how this can cause issues. TypeScript is structurally typed and excess properties create a subtype - which means that, to use this case as an example, the object is actually an |
This is a bug to the extent that the linked issue is a bug (#20863), which is essentially a part duplicate. This comment by @weswigham explains one currently accepted way of dealing with the problem -- you want to specify the properties that should not be present as optionally undefined. |
Somewhat off-topic but just going to throw in that preventing all runtime errors due to incorrect typing ("soundness") isn't even a design goal, and in fact doing so is not even practical. This article might be illuminating: |
That TypeScript narrows it down to At the very least it should infer |
It’s a feature, not a bug, as per the comment linked above:
|
TypeScript Version: 3.3.0-dev.201xxxxx
Search Terms:
Code
Expected behavior:
It shouldn't narrow down the type to
C
since it doesn't match the shape ofC
.Actual behavior:
Compiles fine, even with strict on
Playground Link:
Link
Related Issues:
I think this is related:
#20863
The text was updated successfully, but these errors were encountered: