0

My issue has already been discussed here. My case, however, is slightly different and I'm not sure how to resolve it.

type Filters = {
  short: boolean;
  long: boolean;
};

Then in my function:

const options = {short: false, long: true}
{Object.keys(options).map((option, i) => (
  <Text>{options[option]}</Text>
  ...

I understand that TypeScript cannot use a string as a keyof an object. I tried using the solutions in the thread I mentioned, but I'm getting various errors. I am not quite sure how to use those solutions in my case of a loop. Any ideas?

Ben
  • 2,957
  • 2
  • 27
  • 55
  • An alternative would be using [`Object.entries`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/entries) or [`Object.values`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/values). `Object.entries(options).map(([key, value]) => {})` – known-as-bmf Aug 03 '20 at 18:05
  • @known-as-bmf not really. I am getting the same error since key will inherit exactly the same type (string) as using Object.keys – Ben Aug 03 '20 at 18:09
  • Yes but you won't have to do `options[key]` anymore since the value will already provided in the callback. – known-as-bmf Aug 03 '20 at 18:14
  • @known-as-bmf I see what you mean. This is indeed a possible alternative. In my case it would not work. I abstracted my code for clarity reasons, but I actually NEED to use the key because I'm using it on a different object. ie: ```Object.keys(options).map((option, i) => ({anotherObject[option]}``` – Ben Aug 03 '20 at 18:40

1 Answers1

2

You can cast the Object.keys return type:

(Object.keys(options) as Array<keyof typeof options>)
   .map((option, i) => console.log(options[option]));

as mentioned in this SO answer.

Josef Bláha
  • 1,033
  • 10
  • 21
  • Thank you! Just one adjustment - ```as Array``` will throw a warning. Use ```as (keyof typeof options)[]``` instead – Ben Aug 03 '20 at 18:42