【问题标题】:Typescript How to update every object value打字稿如何更新每个对象值
【发布时间】:2020-04-25 09:30:34
【问题描述】:

我有一个这样的对象:

enum FeatureNames = {
  featureA = 'featureA',
  featureB = 'featureB',
  featureC = 'featureC'
}

interface FeatureDetails {
  on: boolean;
}

type Features = Record<FeatureNames,FeatureDetails>;

const myObj: Features = {
  [FeatureNames.featureA]: {
    on: true
  },
  [FeatureNames.featureB]: {
    on: false
  },
  [FeatureNames.featureC]: {
    on: false
  }
}

如何更新myObj 的每个成员的值,使on 的值为真?

如果没有 typescript,我只会使用 reduce,但是当我尝试这样做时会出现过载错误。

这是错误:

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“记录”。 在“记录”类型上找不到带有“字符串”类型参数的索引签名.ts(7053)

【问题讨论】:

  • 考虑编辑您的代码以构成minimal reproducible example,如How to Ask 所述。 FeatureNames 是什么? FeatureDetails 是什么?您看到什么具体错误以及在什么代码中?

标签: typescript


【解决方案1】:

您可以在 reduce 函数中显式转换 key 参数:

Object.keys(myObj).reduce((obj, key) => (obj[key as FeatureNames].on = true, obj), myObj)

【讨论】:

  • 谢谢!这正是我需要做的。不过做起来超级乏味……
猜你喜欢
  • 2020-08-09
  • 2019-01-13
  • 2021-04-02
  • 2023-03-07
  • 2020-06-25
  • 1970-01-01
  • 2019-04-19
  • 2017-01-22
  • 2019-09-18
相关资源
最近更新 更多