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?

1 Answer 1

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"?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.