Confusion: Type annotation/ Type conversion

Hello, may anyone who has better understand help me digest the following? In both cases the "interface" has one property of the "value" but why does one throw error while one does not? Thanks for any help in advance.
10 Replies
KingCambo
KingCamboOP2y ago
To add: If I assign the object to another variable first, the error disappear which is also confusing.
whatplan
whatplan2y ago
This is because (I forgot the actual term for this, but I will just explain) typescript does not check that objects are exactly as the types you declare. It only checks that they meet the type. In this case any object that has a key year with a value number can be a ‘Year’. Typescript is only ensuring that any variables that exist in that type also exist in the object. The other stuff I don’t really understand what’s happening tbh Also extremely small semantic thing but standard conventions have a space after the colon: ‘const x: string = “foo”’ Legitimately thought you were using some random unknown syntax for a second before I figured it out. Like you do you but just know other devs may be confused at first
KingCambo
KingCamboOP2y ago
Appreciate you a lot for taking the time to answer. Don't mind me but I think the explanation doesn't make sense with my second screenshot, as the property "year" also exist in the object but typescript still throw an error.
KingCambo
KingCamboOP2y ago
For other folks who might be wondering the same thing, I think I've got the answer based on below article. "To recap, excess property checking is only triggered when we define object literals with a type annotation and not in other cases." https://dev.to/this-is-learning/understanding-excess-property-checking-in-typescript-ook
DEV Community
Understanding Excess Property Checking in Typescript
This post was first posted in my newsletter All Things Typescript focused on teaching developers how...
whatplan
whatplan2y ago
yes it appears when you define a object literal these rules dont apply, it must exactly match the type but assignment to another variable does not the first image is just because length isnt capitalized, interface names must be capitalized (in general just use types) actually
whatplan
whatplan2y ago
whatplan
whatplan2y ago
hmmmmmmmmmmmmmmmmm
KingCambo
KingCamboOP2y ago
thank you for the tip and nice recap Weird? I think string is still an object and has a property "length" so it passes but isn't that object literal? idk
whatplan
whatplan2y ago
yup wow thats wild
KingCambo
KingCamboOP2y ago
indeed
Want results from more Discord servers?
Add your server