RecipesChapter 7: Variadic Tuple Types

Creating an Enum from a Tuple

Recipe 7.6 from The TypeScript Cookbook

type Values<T> = T[keyof T];

function createEnum<T extends readonly string[], B extends boolean>(
  arr: T,
  numeric?: B
) {
  let obj: any = {};
  for (let [i, el] of arr.entries()) {
    obj[capitalize(el)] = numeric ? i : el;
  }
  return obj as Enum<T, B>;
}

const Command = createEnum(commandItems, false);
type Command = Values<typeof Command>;
Open in TypeScript Playground →