This behavior is intentional.
The excess property check is not performed when the target is an empty object type since it is rarely the intent to only allow empty objects.
Actually, you can assign {a: 1}
to B, the other answers here are mostly wrong.
You have stumbled upon another slightly confusing quirk in TypeScript, namely that you can not directly assign an object literal to a type where the object literal contains other properties than the one specified in the type.
However, you can assign any existing instance of an object to a type, as long as it fulfill the type.
For example:
interface Animal {
LegCount: number;
}
let dog: Animal = { LegCount: 4, Fur: "Brown" }; // Nope
var myCat = { LegCount: 4, Fur: "Black" };
let theCat: Animal = myCat; // OK
This constraint is simply ignored whey you have a type that is empty.
Read more here and here.
A later answer from the Typescript team is available on GitHub.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…