A common way of dealing with such scenarios is by using an abstraction like Maybe
(sometimes called Option
). Example use:
import { Option } from 'space-lift';
Option(input)
.map(input => input.x)
.map(x => x.y)
.map(y => y.z)
.map(z => z.stringProperty)
.forEach(console.log);
As an alternative, one might use something more succinct like dlv
.
console.log(dlv(input, ['x.y.z.stringProperty']) as string);
Although it might look more appealing due to its compact nature, this solution can never be type-safe. The path expressed as a string cannot be checked against the actual structure of your input
, hence type assertion.