I want to create a generic method in typescript that takes an instance of a type/class/interface and an array of strings and navigates in a nested manner in the array. More precisely, the method can be something like:
method<T>(instance: T, arrayAttr: someType) {
let tmp = undefined;
for (let attr in arrayAttr) {
tmp = instance[attr];
}
return tmp;
}
and I would like to define the someType to check the types and produce an error if the attribute doesn’t exist in the instance.
I tried something like:
type NestedAttributes<T extends InstanceType, U extends keyof T> =
U extends keyof T ? T[U] extends InstanceType ? NestedAttributes<T[U], keyof T[U]> : T[U] : never;
but unfortunately, this is not a good solution