Given the object ;
const t = {
grandmother: {
mother: {
child: 'Peter',
},
},
};
Where i want to retrieve value of key child using
getChildKey(t, 'grandmother.mother.child')
Which works find given the following function
interface NestedObject {
[path: string]: NestedObject | string;
}
const getChildKey = (objectStructure: NestedObject, keyIdentifier: String) => {
const [selectedIdentifier, ...childIdentifier] = keyIdentifier.split('.');
// eslint-disable-next-line no-prototype-builtins
if (objectStructure.hasOwnProperty(selectedIdentifier) && childIdentifier.length > 0) {
if (typeof objectStructure[selectedIdentifier] === 'object') {
return getChildKey(
objectStructure[selectedIdentifier] as NestedObject,
childIdentifier.join('.')
);
}
} else {
return objectStructure[selectedIdentifier];
}
};
I am only to able to resolve the inconsistent return of the function;
TS7023: 'getChildKey' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.
Anyone a suggestion to make this work for any return type of key child? E.g. value of child could be a string, number or object.