Skip to content

Error when destructuring with literal initializers as fallback #26235

Description

@zombie

TypeScript Version: 3.0.1

Destructuring with a fallback empty object literal is a common practice, especially in function arguments (which works), but not always:

Code

type Options = { color?: string; width?: number; };

function A({ color, width }: Options = {}) {
    //
}

function B(options: Options) {
    options = options || {};
    let { color, width } = options;
}

function C(options: Options) {
    let { color, width } = options || {};
}

Expected behavior: All three functions type-check and behave the same.

Actual behavior: "Initializer provides no value for this binding element" Error.

Which is simply incorrect, ES spec clearly defines the value when an object key is missing as undefined. Furthermore, I would argue TS should even accept let { color } = {}; though it's obviously not as common/important.

Related Issues:
Issue #4598 - Improved checking of destructuring with literal initializers fixed the same problem, but only for destructuring function arguments (example A).

Playground Link: here

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions