Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Destructuring an object with not specified fields on type not caught #60714

Open
HoneySpace opened this issue Dec 9, 2024 · 2 comments
Open
Labels
Duplicate An existing issue was already created

Comments

@HoneySpace
Copy link

πŸ”Ž Search Terms

Destructuring object, not specified fields, not caught

πŸ•— Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about Common "Bugs" That Aren't Bugs

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/C4TwDgpgBAglC8UDeBDAXAOwK4FsBGEATgDRR6a4GEC+AULQMYD2GAzsFCgsugIykM0AMxQAbVhGpRGLdmTQAFFIWABLMQB4YAPm6o0AJjrM2HQUpXrRW3YiQA6RymOyOAE0XK1mnXsf2UYkEAZjogA

πŸ’» Code

type A = {a:number, b:number}

const a = {a:1, c:false} 
const b:Partial<A> = {a:2}
const c:Partial<A> = {...a} // doesn't catch field "c" being not specified on type A
const d:Partial<A> = {...a, c:3} // prevents specifying field not from type A

πŸ™ Actual behavior

Object that partially matches type structure was allowed to be destructured into object with defined type, despite having a field that not specified on mentioned type.
Meanwhile when defining not specified field directly on object Typescript will throw an error "Object literal may only specify known properties"

πŸ™‚ Expected behavior

Since object has a not specified property from type, it should throw an error, same as defining a not specified field directly on object
Both destructuring an defining not specified property lead to object have property that doesn't match type structure.

Not catching error when destructuring can easily lead to incorrect behavior, as an example, using function with a lot of parameters that meant to be passed to next function, and describing new property that doesn't exist on type of next function parameters leads function not accounting for this property or even processing it when it shouldn't.

Additional information about the issue

No response

@MartinJohns
Copy link
Contributor

MartinJohns commented Dec 9, 2024

Duplicate of #58835 and many others.

Objects can have additional properties. That's allowed and a TypeScript reality you have to deal with.

@jcalz
Copy link
Contributor

jcalz commented Dec 9, 2024

Terminology note: this is spread, not destructuring.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Dec 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants