Typescript: what could be causing this error? “Element implicitly has an 'any' type because type 'Object' has no index signature”

妖精的绣舞 提交于 2019-12-11 04:48:51

问题


i'm trying to get an array of all the keys in an object with nested properties, my code:

public static getKeys(obj: Object) {
    let keys: string[] = [];
    for (let k in obj) {
        if (typeof obj[k] == "Object" && obj[k] !== null) {
            keys.push(obj[k]);
            CHelpers.getKeys(<Object>obj[k]);
        } else {
            return keys;
        }
    }
}

However, obj[k] is giving me the error "Element implicitly has an 'any' type because type 'Object' has no index signature". i've looked at some other threads with the same error but it seems like their situations are different

i tried the function in playground but it doesn't have this problem there. But in Webstorm and it's giving this error; what could be causing it?


回答1:


I'm pretty sure that this is what you want:

function getKeys(obj: any) {
    let keys: string[] = [];

    for (let k in obj) {
        keys.push(k);
        if (typeof obj[k] == "object") {
            keys = keys.concat(getKeys(obj[k]));
        }
    }

    return keys;
}

Notice that I changed it to push the key itself (k) instead of the value (obj[k]) and the recursive result is concated into the array.
Also, the return keys is now after the for loop, and not in the else.

You shouldn't use Object as a type, instead use any as written in the docs:

You might expect Object to play a similar role, as it does in other languages. But variables of type Object only allow you to assign any value to them - you can’t call arbitrary methods on them, even ones that actually exist.

The function can be simplified using Object.keys:

function getKeys(obj: any) {
    let keys = Object.keys(obj);
    Object.keys(obj).forEach(key => {
        if (typeof obj[key] === "object") {
            keys = keys.concat(getKeys2(obj[key]));
        }
    });

    return keys;
}


来源:https://stackoverflow.com/questions/41929287/typescript-what-could-be-causing-this-error-element-implicitly-has-an-any-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!