With TypeScript, could anyone explain for me why the two function calls below give different type checking result?
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
var myObj = {size: 10, label: "Size 10 Object"};
//This calls is OK
**printLabel(myObj);**
//But this call is warned with error "size doe snot exist in LabelledValue
**printLabel({ size: 10, label: "Size 10 Object" });**
Many thanks.
Typescript allows certain un-sound operations that can’t be known at compile-time to be safe.
Quote from Typescript handbook:
Here obj is type compatible with LabelledValue since obj has all the members LabelledValue require (i.e.
label: string
)However the following gives a compile error since object literal can only specify known properties:
To correct this error, simply explicitly cast the object literal as
<LabelledValue>
: