Skip to content

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

Closed
@jcalz

Description

@jcalz

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.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions