It isn't possible to solve this with deep destructuring. As another answer suggests, it's possible to use default values but they are applied only to undefined
values:
const { credit: { amont } = {} } = userProfile || {};
While null
values still result in error, it's necessary to do short-circuit evaluation for all objects that can potentially be nully:
const { credit } = userProfile || {};
const { amont } = credit || {};
This can be addressed with safe navigation utility function that reads the path and checks for nully values.
A renowned example is Lodash get
:
const amont = _.get(userProfile, 'credit.amont');
I know one way is to use typescript but here I don't
It's possible to address this with TypeScript only if type safety is guaranteed. If userProfile
comes from JSON response, runtime type checks have to be applied to assert that objects aren't null
.