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?