18

I am playing around with Typescript a little.

Suppose I have an object such as this

let colors = {
    RED: "r",
    GREEN: "g",
    BLUE: "b"
}

Now I want to convert this into an enum type

enum Colors = {
    RED = "r",
    GREEN = "g",
    BLUE = "b"
}

Update:

I want the generated typings for the colors object such that if I add another key to the colors object, It should be included in the typings.

If I do

colors['YELLOW'] = "y"

then the generated typings should be

declare enum colors {
    RED = "r",
    GREEN = "g",
    BLUE = "b",
    YELLOW = "y"
}

instead, the generate typings are

declare const colors {
     [x: string]: string        
}

How can I achieve this?

besrabasant
  • 2,422
  • 6
  • 27
  • 41
  • What useage do you have in mind? Don't think you can create an actual enum type based on an object literal, but you can create an object that closely mimicks the behavior of one. – Titian Cernicova-Dragomir Jan 28 '18 at 07:43
  • You can do the opposite - convert `enum` to object – Aleksey L. Jan 28 '18 at 07:51
  • @TitianCernicova-Dragomir I have updated the Question with what I actually want to achieve – besrabasant Jan 28 '18 at 08:01
  • 4
    I expected an Array, not an Object. Your question title is completely unrelated to the body. This would be an Array: `["red", "blue", "green"]` and I would expect it to be converted into a `enum Color { red, blue, green }` – Soldeplata Saketos Jun 30 '21 at 08:33

1 Answers1

4

Enums « Enums allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

TypeScript 2.4+ String enums - Prior to TypeScript 2.4, TypeScript only supported number-based enums in that case just cast the string literal to any before assigning, Using 2.4+ then any would be no longer necessary

enum Colors {
    RED = <any>"R",
    GREEN = <any>"G",
    BLUE = <any>"B",
}

Java script Standard Style

var Colors;
(function (Colors) {
    Colors["RED"] = "r";
    Colors["GREEN"] = "g";
    Colors["BLUE"] = "b";
})(Colors || (Colors = {}));

Check in TypeScript Fiddle fiddlesalad, typescriptlang


Below Utility function to create a K:V from a list of strings may help you.

function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
  return o.reduce((res, key) => {
    res[key] = key;
    return res;
  }, Object.create(null));
}
let dynamicArrayJSON = [ 'RED', 'BLUE', 'GREEN' ]
const Colors = strEnum( dynamicArrayJSON )

@see

Yash
  • 9,250
  • 2
  • 69
  • 74