0

I have a hard time converting a string coming from the env variable to enum.

Here's the enum:

enum Environment {
    Test = 1,
    Development,
    Production
}

export default Environment;

And here's what I've been trying:

export default class GlobalParameters {
    public static Env: Environment = Environment[<string>process.env.NODE_ENV];
}
console.log(process.env.NODE_ENV) // Gives "Development"
let str = String(process.env.NODE_ENV); // Gives "Development"
console.log(Environment[str])  //Gives undefined
Object.seal(GlobalParameters);
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
Emilia Tyl
  • 565
  • 1
  • 5
  • 17
  • Possible duplicate of [How to convert string to enum in TypeScript?](http://stackoverflow.com/questions/17380845/how-to-convert-string-to-enum-in-typescript) – martin Nov 08 '16 at 13:57
  • @martin I'm using this method - creating a string from the env var, however I still get undefined when I try to retrieve an enum – Emilia Tyl Nov 08 '16 at 14:02

2 Answers2

0

Your code seems to work fine:

enum Environment {
    Test = 1,
    Development,
    Production
}

console.log(Environment[2]) // "Development"
let str = String(Environment[2]);
console.log(str); // "Development"
console.log(Environment[str]) // 2

(code in playground)

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • Yes, when I change `let str: string = String(process.env.NODE_ENV);` to `let str: string = String("Development");` It works fine. – Emilia Tyl Nov 08 '16 at 14:11
0

Nevermind, when I was defining the environment variable in the command line it must have added some whitespace characters, because when I changed retrieving string to

let str: string = String(process.env.NODE_ENV).replace(" ", "");

It works fine.

Emilia Tyl
  • 565
  • 1
  • 5
  • 17