Have a look at this example typescript code
function printLabel(labelledObj: { label: string }) {
console.log(labelledObj.label);
}
printLabel({ size: 10, label: 'hello' });
The above code fails to compile with the following error:
1.ts:6:14 - error TS2345: Argument of type '{ size: number; label: string; }' is not assignable to parameter of type '{ label: string; }'. Object literal may only specify known properties, and 'size' does not exist in type '{ label: string; }'.
In short, size
is an excess property and not conforming to the type { label: string }
resulting in compiler yelling. Let's alter the above code snippet a little:
function printLabel(labelledObj: { label: string }) {
console.log(labelledObj.label);
}
const obj = { size: 10, label: 'hello' }
printLabel(obj);
Now we extracted the object literal which was passed to printLabel
in earlier example into an intermediary reference named obj
, the weird part is that now it does not complain and works perfectly. Why does typescript behaves so?