LoginSignup
4
4

More than 5 years have passed since last update.

[typescript] convert string to enum

Posted at

anyにキャストしてから[]でキー指定すればよい。

enum EnumType{
 ONE
}
var one: EnumType = (<any>EnumType)['ONE'];

おまけ

汎用的に使えるヘルパーっぽいの作ったけど記述量は減ってないのでいまいちかも。

playground

enum Beatles{
    JOHN,
    PAUL,
    GEORGE,
    RINGO
}

class Enum{
    static valueOf<E>(value: string, klass: any): E {
        return (<any>klass)[value];
    }
}


var john: Beatles = Enum.valueOf<Beatles>("JOHN", Beatles);

console.log(john == Beatles.JOHN); // true
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4