-
Notifications
You must be signed in to change notification settings - Fork 13k
Open
Labels
Help WantedYou can do thisYou can do thisIn DiscussionNot yet reached consensusNot yet reached consensusSuggestionAn idea for TypeScriptAn idea for TypeScript
Milestone

Description
The following code:
interface Foo {
x: number;
}
interface Bar {
foo?: Foo;
}
function test( { foo: { x } }: Bar ) {
alert( x );
}
test( {} ); // TypeError: Cannot read property 'x' of undefined
transpiles to:
function test(_a) {
var x = _a.foo.x;
alert(x);
}
instead of the (arguably) preferable:
function test(_a) {
var x;
if (_a.foo) x = _a.foo.x;
alert(x);
}
The transpiled code does not check for the presence of optional property foo
in the Bar
interface. This leads to an error at invocation.
I can see three possible solutions:
- Always check for member existence when transpiling destructuring statements.
- Check for member existence only when an element is optional in the interface or type declaration.
- New syntax for destructuring that can indicate members should be checked.
E.g.
function test( { foo?: { x } }: Bar ) {}
Harpush, pkuznetsovdev, arubtsov, yosvelquintero, Woodz and 5 more
Metadata
Metadata
Assignees
Labels
Help WantedYou can do thisYou can do thisIn DiscussionNot yet reached consensusNot yet reached consensusSuggestionAn idea for TypeScriptAn idea for TypeScript