我需要遍历一个对象,并访问它的属性,使用存档查找数组。我想检查密钥的属性是否是instanceof和Array。请考虑以下几点:
const record: MainRecord = {
id: "10",
fieldOne: "Foo",
__typename: "Main",
related: [
{
id: "20",
fieldTwo: "Bar",
__typename: "Related"
},
{
id: "21",
fieldTwo: "Baz",
__typename: "Related"
},
]
}
// Want to iterate over the keys and check for Array type values
// regardless of what the name of the property is.
_.keys(record).map((key) => {
console.log(key);
record["related"] instanceof Array // No TS compiler error.
record["id"] instanceof Array // TS compiler error!
record["id"] as any instanceof Array // This is actually fine apparently.
record[key] instanceof Array // Error! (this is what I'm trying to do)
record[key] as any instanceof Array // ALSO an error. Why is this?
// if(record[key] instanceof Array) {
// // ....
// }
})当我尝试检查instanceof record[key]时,会得到以下编译器错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MainRecord'. No index signature with a parameter of type 'string' was found on type 'MainRecord'.
有什么想法吗?
发布于 2020-09-02 09:33:22
TypeScript编译器在record[key]中抱怨key的类型是string而不是keyof MainRecord,这可能是因为key keys()方法的类型不精确,可能和Object.keys()的类型一样多。
您应该使用类型断言来解决这个问题:
_.keys(record).map(k => {
const key = k as keyof MainRecord;
// if (record[key] instanceof Array) {
// // ....
// }
})https://stackoverflow.com/questions/63696599
复制相似问题