When I define the type of the argument as the type hasLabel
, the code compiles without a problem, despite the fact that myObj
has an extra property, not mentioned by the type:
type hasLabel = {
label:string
}
function printLabel(argumentWithLabel:hasLabel) {
console.log(argumentWithLabel.label);
}
let myObj = { extraProperty: "This is the extra property", label: "This is the label" };
printLabel(myObj);
But when I try to define the type of myObj
as hasLabel
like this:
let myObj:hasLabel = { extraProperty: "This is the extra property", label: "This is the label" };
I get an error: Type '{ extraProperty: string; label: string; }' is not assignable to type 'hasLabel'. Object literal may only specify known properties, and 'extraProperty' does not exist in type 'hasLabel'.
Why does TypeScript let me use an argument that has extra properties, but doesn't let me define a variable the same way?