Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String array to Enum in Typescript

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?

like image 813
besrabasant Avatar asked Jan 28 '18 05:01

besrabasant


1 Answers

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

  • How to create enum like type in TypeScript?
  • Create an enum with string values in Typescript
  • When to use a semicolon in TypeScript?
  • Typescript enum from JSON string
like image 61
Yash Avatar answered Oct 28 '22 16:10

Yash