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:
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 useany
as written in the docs:The function can be simplified using
Object.keys
: