Add functions to an Enum

后端 未结 5 1837
无人共我
无人共我 2020-12-23 10:55

Is it possible to add functions to an Enum type in TypeScript?

for example:

enum Mode {
    landscape,
    portrait,

    // the dream...
    toStri         


        
5条回答
  •  无人及你
    2020-12-23 11:50

    You can either have a class that is separate to the Enum and use it to get things you want, or you can merge a namespace into the Enum and get it all in what looks like the same place.

    Mode Utility Class

    So this isn't exactly what you are after, but this allows you to encapsulate the "Mode to string" behaviour using a static method.

    class ModeUtil {
        public static toString(mode: Mode) {
            return Mode[mode];
        }
    }
    

    You can use it like this:

    const mode = Mode.portrait;
    const x = ModeUtil.toString(mode);
    console.log(x);
    

    Mode Enum/Namespace Merge

    You can merge a namespace with the Enum in order to create what looks like an Enum with additional methods:

    enum Mode {
        X,
        Y
    }
    
    namespace Mode {
        export function toString(mode: Mode): string {
            return Mode[mode];
        }
    
        export function parse(mode: string): Mode {
            return Mode[mode];
        }
    }
    
    const mode = Mode.X;
    
    const str = Mode.toString(mode);
    alert(str);
    
    const m = Mode.parse(str);
    alert(m);
    

提交回复
热议问题