bcherny
bcherny

Reputation: 3172

Why does this TypeScript code fail to typecheck?

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

https://www.typescriptlang.org/play/index.html#src=let%20a%3A%20%7B%20b%3A%20number%20%7D%0D%0Alet%20b%3A%20%7B%20b%3A%20number%2C%20c%3A%20number%20%7D%20%3D%20%7B%20b%3A%201%2C%20c%3A%202%20%7D%0D%0Aa%20%3D%20%7B%20b%3A%201%2C%20c%3A%202%20%7D%20%2F%2F%20Error%3A%20Object%20literal%20may%20only%20specify%20known%20properties%0D%0Aa%20%3D%20b%20%2F%2F%20Ok%0D%0A

Upvotes: 1

Views: 48

Answers (2)

dimvar
dimvar

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

Robby Cornelissen
Robby Cornelissen

Reputation: 97331

The error message says it all.

  1. The first case fails because an "[o]bject literal may only specify known properties", and c isn't a known property of a.

  2. The second case succeeds because b is not an object literal, so the above rule doesn't apply.

Upvotes: 1

Related Questions