Iterate over generic enum Types Typescript

Viewed 720

I stumbled across a problem I have which is that I need to iterate over generic enum Types. I'm trying to get the values of the enum Type.

Typescript error in GetPaths function in the for loop parameters:

"'T' only refers to a type, but is being used as a value here"

export enum ERoutingPaths {
  Home = "/",
  About = "/About"
}

export enum EGamePaths {
  Snake = "/Snake",
  Maze = "/Maze",
}

 function GetPaths<T extends ERoutingPaths | EGamePaths>():any {
  let result = "";
  for (let item in Object.values(T))  {
    result += item + "|";
  }
  return result;
}

How can I make a function which allows me to iterate over a generic enum type if I would have other enum types aswell ?

1 Answers

Enums with string values are old plain JavaScript objects with strict key-value typing. You may use Record<string, string> type.

function GetPaths(value: Record<string, string>): string {
  let result = "";
  for (let item in value) {
    result += value[item] + "|";
  }
  return result;
}

If you want to only allow a strict set of types here you may stay with generics and use: T extends typeof ERoutingPaths | typeof EGamePaths. Notice a word typeof - we have to extract a type from an enum. There is also one more change needed.

for (let item in value) {
   result += value[item as keyof T] + "|";
}

TypeScript widens item type to string - compiler doesn't allow using strings with enums so I'm casting it back to keyof T.

Related