a person
a person

Reputation: 1706

Typescript How to update every object value

I have a object like this:

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
  }
}

How can I update the value of every member of myObj so the on value is true?

Without typescript I would just use reduce, but I get a overload error when I try to do so.

Here's the error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record'. No index signature with a parameter of type 'string' was found on type 'Record'.ts(7053)

Upvotes: 1

Views: 1013

Answers (1)

iY1NQ
iY1NQ

Reputation: 2514

You can explicit cast the key argument within the reduce function:

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

Upvotes: 3

Related Questions