首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >索引签名在使用

索引签名在使用
EN

Stack Overflow用户
提问于 2020-09-01 23:10:06
回答 1查看 84关注 0票数 0

我需要遍历一个对象,并访问它的属性,使用存档查找数组。我想检查密钥的属性是否是instanceofArray。请考虑以下几点:

代码语言:javascript
复制
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'.

有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-02 09:33:22

TypeScript编译器在record[key]中抱怨key的类型是string而不是keyof MainRecord,这可能是因为key keys()方法的类型不精确,可能和Object.keys()的类型一样多。

您应该使用类型断言来解决这个问题:

代码语言:javascript
复制
_.keys(record).map(k => {
  const key = k as keyof MainRecord;
  // if (record[key] instanceof Array) {
  //   // ....
  // }      
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63696599

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档