Jim_Mcdonalds
Jim_Mcdonalds

Reputation: 496

Spread Operation and Typescript Phenomenon

I am quite new to typescript, can someone please explain why typescript can't detect the following error? A method's parameter accepts an object with 3 properties but there was no typescript error when an object with 4 properties was passed in.

 const consoleLog = (params: { a: number; b: number; c: number }): void => {
    console.log(params);
  };
  const test = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
  };
  consoleLog({ ...test });

Thank you.

Upvotes: 1

Views: 65

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85122

No error is thrown, because the object you're passing in is compatible with the one the function expects.

(params: { a: number; b: number; c: number }) means that the object needs to have an a property, a b property, and a c property, with each of them being numbers. It doesn't mean that those are the only properties the object can have; it's fine to pass in an object with additional properties.

For more information on type compatibility, see this page (emphasis added in the following quote):

The basic rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x.

Upvotes: 1

Related Questions