【发布时间】:2022-02-04 17:17:27
【问题描述】:
给定对象;
const t = {
grandmother: {
mother: {
child: 'Peter',
},
},
};
我想在哪里检索 key child 的值
getChildKey(t, 'grandmother.mother.child')
根据以下功能找到哪些工作
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];
}
};
我只能解决函数返回不一致的问题;
TS7023:“getChildKey”隐含返回类型“any”,因为它没有返回类型注释,并且在其返回表达式之一中直接或间接引用。
任何人建议使这项工作适用于任何返回类型的关键子项?例如。 child 的值可以是字符串、数字或对象。
【问题讨论】:
-
这个问题可能与您高度相关:stackoverflow.com/questions/69126879/…
-
我不认为不可能以类型安全的方式实现您的请求,但这可能不切实际。如果您能以这种方式重构它,像
getChildKey(t, ['grandmother', 'mother', 'child'])这样的签名可能会使输入变得更容易。然而,对于括号访问器索引而言,所有这些似乎都是一种仪式(例如t['grandmother']['mother']['child'])。点中缀访问器是运行时某种类型的用户输入吗? -
点中缀访问器是作为对象键值的字符串。配置文件的排序。
标签: typescript recursion