Looking to implement a TypeScript method that can navigate through nested arrays of strings when given an instance of a type/class/interface. The method, in concept, should resemble:
method<T>(instance: T, arrayAttr: someType) {
let tmp = undefined;
for (let attr in arrayAttr) {
tmp = instance[attr];
}
return tmp;
}
I want to designate the someType
to enforce type checking and generate errors if an attribute does not exist within the instance.
For example, with the object:
const obj = {
attribute1: {
attribute2: {
attribute3: "value"
}
}
};
The method call:
method(obj, ['attribute1', 'attribute2', 'attribute3'])
should yield 'value'. Conversely, invoking the method with incorrect attributes:
method(obj, ['attribute1', 'attribute3'])
it should result in a compilation error.
One attempt I made was with this snippet:
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;
However, this solution proved less than ideal.