Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does typescript throw an error when assigning an object directly but not when assigning it through a third variable?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The error is cause by the excess property check on literal objects (docs). The documentation is a little sparse on the reasoning behind it though, which is not 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading