Reputation: 3172
let a: { b: number }
let b: { b: number, c: number } = { b: 1, c: 2 }
a = { b: 1, c: 2 } // Error: Object literal may only specify known properties
a = b // OK
Upvotes: 1
Views: 48
Reputation: 581
Typescript supports structural typing. When checking whether an object type B is a subtype of an object type A, excess properties of B don't matter. In an effort to catch more bugs, Typescript has a special case when it knows that the type B comes from an object literal. These are called fresh object literals, and are described here. The rationale is that the excess property is usually a typo. But when the type B can come from any object, not just an object literal, the usual structural typing rules apply, so there is no warning.
Upvotes: 2
Reputation: 97331
The error message says it all.
The first case fails because an "[o]bject literal may only specify known properties", and c
isn't a known property of a
.
The second case succeeds because b
is not an object literal, so the above rule doesn't apply.
Upvotes: 1