Reverse-Mapping for String Enums

后端 未结 4 690
星月不相逢
星月不相逢 2020-12-05 23:12

I wanted to use string enums in typescript but I can\'t see a support for reversed mapping in it. I have an enum like this:

enum Mode {
    Silent = \"Silent         


        
4条回答
  •  囚心锁ツ
    2020-12-05 23:50

    The cleanest way I found so far is to make a secondary map:

    let reverseMode = new Map();
    Object.keys(Mode).forEach((mode: Mode) => {
        const modeValue: string = Mode[mode];
        reverseMode.set(modeValue, mode);
    });
    

    Thus you can do let mode: Mode = reverseMode.get('Silent');

    Advantages: no need to repeat the values, provides a way to enumerate the enum, keeps TSLint happy...

    Edit: I originally write Mode[mode] but then TS might throw the error TS7015 on this line, so I added the cast.

提交回复
热议问题