Accessing properties of optional properties is always a hassle. Imagine the following object test1
(in TypeScript notation):
interface Test {
a?: { b?: { c?: { d?: string } } };
}
const test1: Test = { a: { b: { c: { d: 'e' } } } };
The absence of each property has to be handled in order to receive the 'e'
if it is there to avoid an error, eg.:
let result;
const test2: Test = { a: { b: {} } };
Trying to accessing the property d
directly would throw an error, since c
is undefined
and obviously that has no property d
.
result = test2.a.b.c.d // TypeError: undefined is not an object
So every property has to be checked manually:
let result;
if (test2 && test2.a && test2.a.b && test2.a.b.c && test2.a.b.c.d !== undefined) {
result = test2.a.b.c.d;
}
What is the shortest and a best practice solution for this common problem?
A try/catch
block could work, but does not seem to be short. Passing the test2.a.b.c.d
as a function argument to a function handling the error also does not seem to work, since it would throw the error before entering the function.