[英]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". 但是,obj [k]给出了错误“Element隐式具有'any'类型,因为类型'Object'没有索引签名”。 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; 但是在Webstorm中,它给出了这个错误; 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. 请注意,我将其更改为按键本身( k
)而不是值( obj[k]
),并将递归结果合并到数组中。
Also, the return keys
is now after the for loop, and not in the else. 此外, return keys
现在在for循环之后,而不是在else中。
You shouldn't use Object
as a type, instead use any
as written in the docs : 您不应该使用Object
作为类型,而是使用文档中所写的 any
:
You might expect Object to play a similar role, as it does in other languages. 您可能希望Object扮演类似的角色,就像在其他语言中一样。 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. 但是Object类型的变量只允许你为它们分配任何值 - 你不能在它们上调用任意方法,即使是实际存在的方法。
The function can be simplified using Object.keys
: 使用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.