【问题标题】:How to resolve Typescript TS7023 in recursive function如何在递归函数中解析 Typescript TS7023
【发布时间】: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


【解决方案1】:

感谢 jsejcksn 采用了完全不同的方法;

const getNestedValue = (
    objectStructure: { [key: string]: any },
    keyIdentifier: Array<string>
) => {
    let returnObj = objectStructure;
    const valueFound = Object.values(keyIdentifier).every((objKey) => {
        if (returnObj[objKey]) {
            returnObj = returnObj[objKey];
            return true;
        }
        return false;
    });

    return valueFound ? returnObj : undefined;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2016-10-24
    相关资源
    最近更新 更多