Destructuring causes error for null/undefined properties
See original GitHub issueThe 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 ) {}
Issue Analytics
- State:
- Created 8 years ago
- Reactions:7
- Comments:22 (10 by maintainers)
Top Results From Across the Web
Prevent Error with Default {} when Destructuring
You have to check for TypeError and then make sure it's a TypeError around reading a property of undefined or null. That way...
Read more >Cannot destructure Property of Null Error in JavaScript
The "Cannot destructure property of null" error occurs when we try to destructure a property from a null value. To solve the error,...
Read more >JS/ES6: Destructuring of undefined - javascript - Stack Overflow
Note: The default value would only be applied if the destructured param is undefined , which means that destructuring null values will throw...
Read more >TIL: Destructuring from an Object with a possibly Undefined ...
Destructure from a possibly undefined object property. Problem ... undefined (not good, we needed this to be null)// Result: FAILURE.
Read more >Optional chaining (?.) - JavaScript - MDN Web Docs - Mozilla
The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish ( null...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
What’s the current status of this?
I think you also have the problem when destructuring arrays.
TypeScript will consider all three variables to be
string
while they should bestring | undefined
(because, they are totallyundefined
here)