0

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
oneday
  • 1,599
  • 5
  • 18
  • 29
  • 1
    Please see [docs](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks) . `Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. If an object literal has any properties that the “target type” doesn’t have, you’ll get an error` – captain-yossarian from Ukraine Jul 13 '22 at 07:26
  • Because interface segregation. If an object is only accessible through a single interface then extra properties are obviously not right, but that's not true in the general case. – jonrsharpe Jul 13 '22 at 07:27
  • @VLAZ I think so, thank you! It seems the person asking the question got puzzled in the very same moment of the very same tutorial. – oneday Jul 13 '22 at 08:13

0 Answers0