Skip to content

Immediately destructuring a spread union allows access to properties not present in all union constituents #43174

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

Closed
jcalz opened this issue Mar 10, 2021 · 0 comments Β· Fixed by #43783
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@jcalz
Copy link
Contributor

jcalz commented Mar 10, 2021

Bug Report

πŸ”Ž Search Terms

spread, destructuring, union

πŸ•— Version & Regression Information

⏯ Playground Link

Playground link

πŸ’» Code

interface A { a: string }
interface B { b: number }

function foo(x: A | B) {
    const { a } = { ...x } // no error?! 
    // const a: string | undefined
    a?.toUpperCase();
}

const x = { a: 1, b: 2 }
foo(x); // a.toUpperCase is not a function, oops

πŸ™ Actual behavior

There is no error; a is inferred to be of type string | undefined.

πŸ™‚ Expected behavior

I expected an error on destructuring assignment to a saying Property 'a' does not exist on type 'A | B', as you would get with the seemingly equivalent construction without spreading

const { a } = x; // error! Property 'a' does not exist on type 'A | B'.

or the also-seemingly-equivalent construction with an intermediate variable

const v = { ...x }
const { a } = v; // error! Property 'a' does not exist on type '{ a: string; } | { b: number; }'

I figure this is a side effect of #31711. But is it considered a bug? a design limitation? or working as intended? Comes from this SO question.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
4 participants