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?
It's by design. In short, Typescript creators made it this way because they know Javascript is a very dynamic language with many such use cases.
You should read this carefully: https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks (however I bet the question arised from reading it).
Object literals get special treatment
Their logic might be like this: if you have a variable, then it may come from some third party and there is not much you can do with it. On the other hand, if you pass an object literal, then you are responsible for its correct type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With