When working with Lodash, one common function utilized is get
, which allows for retrieval of nested properties in objects like this:
_.get(object, 'a[0].b.c');
// => 3
_.get(object, ['a', '0', 'b', 'c']);
// => 3
_.get(object, 'a.b.c', 'default');
An issue often encountered with this approach is the lack of type safety when using TypeScript, as it does not prevent potential typos. Thus, I am exploring alternative ways to achieve similar functionality without relying on strings.
const obj = {a: {b: {c: {}}}, b: {}};
const a = get(obj, obj => obj.a.b.c.d.g, 'defaultValue');
function get(obj: T, getFn, defaultValue) {
try {
return getFn(obj);
} catch(err) {
return defaultValue;
}
}
Is this the recommended method or are there better approaches available?