如何解决尝试使用instanceof比较值时,索引签名不起作用
我需要遍历一个对象并使用lodash访问其属性以查找数组。我想检查键的属性是否为instanceof
和Array
。请考虑以下内容:
const record: MainRecord = {
id: "10",fieldOne: "Foo",__typename: "Main",related: [
{
id: "20",fieldTwo: "Bar",__typename: "Related"
},{
id: "21",fieldTwo: "Baz",]
}
// 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'.
有什么想法吗?
解决方法
TypeScript编译器抱怨record[key]
具有key
类型而不是string
类型,keyof MainRecord
可能是因为lodash keys()
方法的输入不精确,可能与Object.keys()
的类型一样多。
您应该使用类型断言来解决此问题:
_.keys(record).map(k => {
const key = k as keyof MainRecord;
// if (record[key] instanceof Array) {
// // ....
// }
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。