-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Possible bug: Hybrid between two interfaces of a union passes type checking #14383
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
This is working as intended. The type const x: Baz = {
foo: 'foo', // Error, excess property
baz: 'foo',
}; This is because when the target is a union type our excess property check for object literals (#3823) only checks that each property exists in some variant of the target. It should perhaps be stricter and check that the source is assignable to at least one variant with no excess properties (which would then error on your example). |
@ahejlsberg Ah, okay that makes sense I suppose. I'm admittedly ignorant as to how much added complexity it would take to add the stricter checking but, intuitively speaking, I would assume the example above to only compile successfully with interfaces having an index signature. The use-case I had when I ran into this issue was when I was attempting to create a function parameter that accepted two different forms of authentication: One being basic username and password auth (in which case, both of these fields is required), and the other being browser cookie authentication where only a single field is required. I ended up just creating a union between a Thanks for the education on this. |
I'd love to see these stricter checks at some point - any way to work around this issue without changing the types themselves? I'm trying to validate some existing data, and I can describe all the types I need, but the lack of the stricter check lets bad data through.
|
Some relevant discussion of this at #12936 (comment) |
TypeScript Version: 2.1.1 / nightly (2.2.0-dev.20170228)
Went to StackOverflow with this first and the consensus there seems to be that this is a bug.
Here's my question again for convenience:
Consider a situation where an object can have exactly the
FooBar
orBaz
interface listed below.It's my understanding that this "one or the other" situation can be handled by creating a union between
FooBar
andBaz
.So far so good...
The issue I'm having is that the following object passes type checking:
Expected behavior:
x
should not pass type checking. It's neitherFooBar
norBaz
, but rather a combination between the two.Actual behavior:
x
passes type checking.Playground Example
The text was updated successfully, but these errors were encountered: