For a long time we've been having a problem that the only way to access a nested property safely and easily is to use _.get. Ex:
_.get(obj, "Some.Nested[2].Property", defaultValue);
This works great, but doesn't stand up to property renames as frequently happens. Theoretically, it should be possible to transform the above into the following and allow TypeScript to implicitly type check it:
safeGet(obj, "Some", "Nested", 2, "Property", defaultValue);
I've been successful in creating such a typing for everything except for array types:
function getSafe<TObject, P1 extends keyof TObject>(obj: TObject, p1: P1): TObject[P1];
function getSafe<TObject, P1 extends keyof TObject, P2 extends keyof TObject[P1]>(obj: TObject, p1: P1, p2: P2): TObject[P1][P2];
This properly checks for items at depth (I will auto generate these statements to 10 levels or so). It fails with array properties because the type passed into the next parameter is T[] and not T.
The complexity or verbosity of any solution is of no consideration as the code will be auto generated, the problem is that I can't seem to find any combination of type declarations which will allow me to accept an integer parameter and deconstruct the array type moving forward.
You can deconstruct an array (where T is an array) using T[number]. The problem is that I have no way to constrain where T is an array on a nested property.
function getSafe<TObject, P1 extends keyof TObject, P2 extends keyof TObject[P1][number]>(obj: TObject, p1: P1, index: number, p2: P2): TObject[P1][number][P2];
^^^^^^ ^^^^^^
const test2 = getSafe(obj, "Employment", 0, "Id"); // example usage
That actually works at the call-site (no errors there, correctly gives us param and return types), but gives us an error in the declaration itself because you can't index TObject[P1] with [number] as we can't guarantee TObject[P1] is an array.
(Note: TType[number] is a viable way to get the element type from an array type, but we need to convince the compiler that we're doing this to an array)
The question is really, would there be away to add a array constraint to TObject[P1] or is there another way to do this that I'm missing.