There're similar questions here and I can understand the nature of this error:
type Person = { name: string };
// Error: Object literal may only specify known properties, and 'age' does not exist in type 'Person'.
const person: Person = { name: 'Sarah', age: 13 };
So this fails, because property age
is not a part of type Person
which makes sense.
However, I can do this without any problems:
type Person = { name: string };
const obj = { name: 'Sarah', age: 13 };
const person: Person = obj;
console.log(person); // { name: 'Sarah', age: 13 }
Why the first one is failing and the second is not - shouldn't these 2 examples both fail or both pass?
As for me these 2 code snippets are identical. Aren't they?
Update:
Here's an explanation of this behaviour from Typescript Handbook:
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.
As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.
Basically: the TS compiler knows that the age will never be used, thats why its angry at you. In the second example it doesnt know that age will never be used as its part of a normal object. Once it gets copied to the Person only the name continues to exist
TLDR: when initializing with a literal the TSC is strict
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With