简体   繁体   中英

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

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM