【问题标题】:How to iterate object using typescript如何使用打字稿迭代对象
【发布时间】:2020-03-04 17:41:22
【问题描述】:

我是打字稿语言的新手,我尝试使用打字稿迭代对象。但它抛出了一个错误,如何处理这个错误。
[typescript] 元素隐含地具有“任何”类型,因为 type '{ a: string; b:字符串; c:字符串; }' 没有索引签名。

代码

var obj = {
  a: ' a',
  b: 'b ',
  c: ' c '
};

Object.keys(obj).map(k => obj[k] = obj[k].trim());
console.log(obj);

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以尝试为变量 obj 创建一个接口,以便 TypeScript 编译器知道您的键/属性和值的类型。

    interface TheObject {
        [key: string]: string;
    }
    
    const obj: TheObject = {
      a: ' a',
      b: 'b ',
      c: ' c '
    };
    

    显示以下错误 ([typescript] Element implicitly has an 'any' type because type '{ a: string; b: string; c: string; }' has no index signature.) 的原因是因为 TypeScript 不知道 index signature,因为您原来的 obj 没有输入,因此它被定义为 any,这意味着它可能没有可迭代。

    【讨论】:

      【解决方案2】:

      你可以像这样使用 for in 循环来迭代对象

      for (var key in obj){
          obj[key] = obj[key].trim()
          console.log(obj[key])
      }
      

      【讨论】:

        猜你喜欢
        • 2016-11-25
        • 1970-01-01
        • 2022-12-14
        • 2022-12-05
        • 2017-05-12
        • 2020-06-22
        • 1970-01-01
        • 1970-01-01
        • 2020-07-26
        相关资源
        最近更新 更多