1

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)

1
  • Consider editing your code to constitute a minimal reproducible example as described by How to Ask. What's FeatureNames? What's FeatureDetails? What specific error do you see and in what code? Commented Jan 7, 2020 at 20:49

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's exactly what I needed to do. It is super tedious to do though...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.