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.
In the first case, typescript implicitly casts an object of type
{ size: number, label: string }toLabelledValue, which works fine.In the second case, typescript thinks you are trying to create an object of type
LabelledValue, so it gets mad becausesizeis not a valid property.You would get the same error in the first case if you assigned a type to
myObj, e.g.I don't know what you are trying to do with this, but one possible workaround would be to add
sizeas an optional property of your interface, like this: