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?
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
enum from JSON stringIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With