【问题标题】:Index signature for iteration in typescript打字稿中迭代的索引签名
【发布时间】:2020-02-19 15:21:15
【问题描述】:

我们都可以看到这段代码是有效的javascript:

const myObj = {
  foo: "string",
  bar: 123,
  baz: "important stuff"
};

['foo', 'bar'].forEach((key) => {
  delete myObj[key];
});

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ foo: string;酒吧:数字; baz:字符串; }'。 在类型 '{ foo: string; 上找不到具有类型参数的索引签名。酒吧:数字; baz:字符串; }'。

那么,实现这种 TypeScript 兼容的最佳方式是什么?

【问题讨论】:

标签: typescript index-signature


【解决方案1】:

尝试输入您的数组:

const myObj = {
  foo: "string",
  bar: 123,
  baz: "important stuff"
};

const myArray: (keyof typeof myObj)[] = ['foo', 'bar']

myArray.forEach(...)

【讨论】:

    【解决方案2】:

    一种解决方法是:

    (['foo', 'bar'] as (keyof typeof myObj)[]).forEach((key) => {
      delete myObj[key];
    });
    

    但它并不能防止在数组字符串中输入错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 2021-03-06
      相关资源
      最近更新 更多