0

I get an error as expected, when passing an array with object literals to a function, because they do not have a corresponding property in the type they're being assigned to.

type hasAge = {
  age: number;
};

function getOldest(items: hasAge[]): hasAge {
  return items.sort((a, b) => b.age - a.age)[0];
}

let oldest = getOldest([
  { age: 22, name: "Pete" },
  { age: 87, name: "Daniel" },
  { age: 36, name: "Jessica" },
]); //Type error - Object literal may only specify known properties

No problems will be detected, when passing an array as a variable:

let people = [
  { age: 22, name: "Pete" },
  { age: 87, name: "Daniel" },
  { age: 36, name: "Jessica" },
];
let oldest = getOldest(people);

Even destructuring the array is not going to cause a problem:

let people = [
  { age: 22, name: "Pete" },
  { age: 87, name: "Daniel" },
  { age: 36, name: "Jessica" },
];
let oldest = getOldest([...people]);

What am i missing? Aren't all function calls basically the same?

FelHa
  • 1,043
  • 11
  • 24

1 Answers1

1

when you pass an array typescript is using duck typing and therefore it is only bothering with required attributes, not the extra ones. https://www.typescriptlang.org/docs/handbook/interfaces.html

for the first case when you use object literal see this Why am I getting an error "Object literal may only specify known properties"?

Negi007
  • 51
  • 1
  • 5