0

I have the next code:

enum MyEnum {
  Colors = 'AreColors',
  Cars = 'AreCars',
}

const menuTitle = ((obj: MyEnum) => {
  const newObj = {};
  Object.keys(obj).forEach((x) => {
    newObj[obj[x]] = x;
  });
  return newObj;
});

Here i want to change the enum keys in place of enum values.
Doing this i get Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}' here newObj[obj[x]] = x;.
Why the issue appears and how to solve?

Asking
  • 3,487
  • 11
  • 51
  • 106

1 Answers1

2

There are several issues of your code:

  1. If you want to invert the key-value pairs of the enum by passing in MyEnum as the object, then you need to use obj: typeof MyEnum. This is assuming you want to use menuTitle(MyEnum) to perform the inversion.
  2. Object.keys(obj) will return an array of strings and this causes indexing issues with your enum. If you cast it to an array of keyof typeof MyEnum then it will work.

Improved code:

enum MyEnum {
  Colors = 'AreColors',
  Cars = 'AreCars',
}

const menuTitle = ((obj: typeof MyEnum) => {
  const newObj: { [key in MyEnum]?: keyof typeof MyEnum } = {};
  (Object.keys(obj) as Array<keyof typeof MyEnum>).forEach((x) => {
    newObj[obj[x]] = x;
  });
  return newObj;
});

console.log(menuTitle(MyEnum));

See proof-of-concept example on TypeScript Playground.

Terry
  • 63,248
  • 15
  • 96
  • 118