尝试使用instanceof比较值时,索引签名不起作用

问题描述

我需要遍历一个对象并使用lodash访问其属性以查找数组。我想检查键的属性是否为instanceofArray。请考虑以下内容

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) {
  //   // ....
  // }      
})