Home > Mobile >  Why does typescript throw an error when assigning an object directly but not when assigning it throu
Why does typescript throw an error when assigning an object directly but not when assigning it throu

Time:03-17

I have the following piece of code:

interface User {
  id: number; 
  name: string;
}

const newUser = {id: 5, name: "Tom", age: 22}

// throws no error
const user1: User = newUser

// throws:
// Type '{ id: number; name: string; age: number; }' is not assignable to type 'User'.
//   Object literal may only specify known properties, and 'age' does not exist in type 'User'.
const user2: User = {id: 5, name: "Tom", age: 22}

TS Playground

Why is the first assignment ok and the second one not, even though they do pretty much the same thing?

CodePudding user response:

The error comes from the excess-property check on literal objects (docs). The documentation is a little sparse on the reasoning behind it though, which is not actually that complex.

In the first example, newUser may appear in other parts of the code besides the assignment to user1, so even though we won't access age on user1, it may still be accessed elsewhere.

For the second example this is not the case. The age property cannot be accessed on user2, which means there is no typed way to access this property, and it is most likely an error.

  • Related