-1
type User = {
  firstName: string

}
const foo = (u: User) => null
const someUser = {
  firstName: "first",
  lastName: "last",
}
foo(someUser) // passes
foo({  // breaks
    firstName: "first",
    lastName: "last"
})

Playground

Why does typescript break when calling the function with explicit args:

Argument of type '{ firstName: string; lastName: string; }' is not assignable to parameter of type 'User'.
  Object literal may only specify known properties, and 'lastName' does not exist in type 'User'.(2345)

but not when passing an object?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
itaied
  • 119
  • 1
  • 1
  • 6
  • Because when you inline the object literal you get _excess property checks_. If you typed the `user` variable you'd get the same thing. – jonrsharpe Jun 01 '22 at 15:02
  • Does this answer your question? [Why am I getting an error "Object literal may only specify known properties"?](https://stackoverflow.com/questions/31816061/why-am-i-getting-an-error-object-literal-may-only-specify-known-properties) – Etheryte Jun 01 '22 at 15:06

1 Answers1

0

From the manual:

You could argue that this program is correctly typed, since the width properties are compatible, there’s no color property present, and the extra colour property is insignificant.

However, TypeScript takes the stance that there’s probably a bug in this code. Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. If an object literal has any properties that the “target type” doesn’t have, you’ll get an error:

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335