1

I'm currently learning TypeScript and I'm not entirely sure when an interface is a fixed contract and when it simply defines minimum requirements. Here's an example:

interface Animal {
  name: string;
}

const func = (arg: Animal) => {};

const obj = {
  name: "tom",
  bark: () => undefined,
}

func(obj); // -> OK
func({
  name: "tom",
  bark: () => undefined, // -> NOT OK
})
func({...obj}) // -> OK

As you can see, passing a variable to (func(obj)) simply defines minimum requirements for the object's interface. In this case, the object needs to have a name property BUT can have additional properties attached to it.

However, if I create the object literal as part of the function call (func({...})), the relationship is more like a fixed contract where the object needs to have the exact same properties as Animal. In this case, I CAN NOT pass an object with any additional properties.

Is there any rule as to when an interface is a fixed contract vs. minimum requirements?

Xen_mar
  • 8,330
  • 11
  • 51
  • 74
  • 1
    It's related to [excess property checks](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks) - that feature is *only* used when directly defining the object as you pass it. For example, `myFunc({foo: "hello", bar: "world"})` will perform an excess property check, while `myFunc(myObj)` would not. – VLAZ May 27 '21 at 12:39
  • 1
    [Why can I avoid excess property check in typescript just by passing a reference to an object to a function rather than the object in its literal form?](https://stackoverflow.com/q/52852278) | [Empty interface allow any object?](https://stackoverflow.com/q/42537727) | [Typescript: prevent assignment of object with more properties than is specified in target interface](https://stackoverflow.com/q/57497299) | [Forcing excess-property checking on variable passed to TypeScript function](https://stackoverflow.com/q/54775790) | [How excess property check helps?](https://stackoverflow.com/q/50143250) – VLAZ May 27 '21 at 12:50
  • That really helped. Interestingly enough, I've read this part of the documentation before posting (but the current section). For newer versions, the section on excess property checking seems to have been removed. – Xen_mar May 27 '21 at 12:53
  • Yeah, I agree that's inconvenient. That's why I linked you to the deprecated one. It's still relevant - I don't know why it's not included in the new version. Might be an omission or it's in a different section or something. – VLAZ May 27 '21 at 12:55

0 Answers0