Typescript (or should we say ES) doesn't allow destructuring of null/undefined objects. It throws TypeError.
So, lets say we have something like
let {a,b,c} = D;
where D
could be null
.
If we need to do conditional destructuring assignment with null-checks then we create boilerplate code for something that was meant to reduce it.
What is the most elegant way of using it in cases like that or should we use destructuring only for guaranteed non-null objects?
wait wait...but Object can be nullable. What then? You can use an empty object as fallback, and if D is null or undefined the assigned variables will be undefined. Using typescript you need to add the correct type (or any) to the FALLBACK object ( TS playground ). For example:
Here’s a breakdown (or build up) to my object, with destructuring along the way. For the simplest object (like I outlined above when defining destructuring), it looks like this: Right, that seems logical, access the property’s value in the object just by wrapping that property in curly braces. Next, up…
// an objectconstJohn = { age: 23, isAdult: true, }; // get age property using destructuring syntaxconst{ age } = John; To set or define a type on the age property we can use a colon :after the destructuring operator and then open a curly brace and then define the type of the ageproperty inside that curly brace like this,
Beginning with C# 7.0, you can use the is operator with a type pattern to both examine an instance of a nullable value type for null and retrieve a value of an underlying type: You always can use the following read-only properties to examine and get a value of a nullable value type variable:
You can use an empty object as fallback, and if D
is null
or undefined
the assigned variables will be undefined
.
const D = null;
const { a, b, c } = D || {};
console.log(a, b, c);
Using typescript you need to add the correct type (or any
) to the FALLBACK object (TS playground). For example:
interface Obj {
a?: string;
b?: string;
c?: string;
}
const D = null;
const { a, b, c } = D || {} as Obj;
console.log(a, b, c);
Another option is to use object spread, since spreading null
or undefined
results in an empty object (see this SO answer).
const D = null;
const { a, b, c } = { ...D };
console.log(a, b, c);
Using typescript you need to add the types to the variable that you spread, and the object that you destructure. For example (TS Playground):
interface Obj {
a?: string;
b?: string;
c?: string;
}
const D = null;
const { a, b, c } = { ...D as any } as Obj;
console.log(a, b, c);
If you need to handle nested destructuring, use defaults:
const D = null;
const { a, a: { z } = {}, b, c } = { ...D };
console.log(a, b, c, z);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With