Reputation: 200
interface X {
a: number;
}
const x: X = {
a: 9,
// somethingElse: 8 // This would result in compilation error as expected
};
const y = {
a: 9,
somethingElse: 8
};
const xx: X = y; // but this works
However, I would expect the same behavior as the first assignment, resulting in compilation error because of the extra property.
Upvotes: 1
Views: 220
Reputation: 23174
The rationale I understand is this way :
When defining directly your x: X
, the additional property somethingElse
should never be accessed, that seem to be the intent when typing this as X
.
All along in the rest of the code x
will always be of type X
and it does not expose somethingElse
, so, for the compiler, here it's the code (or the developer ;) ) that is inconsistent.
When you assign the other varriable xx
with y
, y
was not explicitly typed, and thus the property somethingElse
could still be used in other places.
For the compiler, you seem to temporarily restrict y
to the part that matches the interface X
, and that's nice. In a more complicated example maybe many different objects could fit this role, so the specific interface typing for xx
is perfectly legitimate.
Upvotes: 1