Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
830 views
in Technique[技术] by (71.8m points)

typescript - Add functions to an Enum

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

for example:

enum Mode {
    landscape,
    portrait,

    // the dream...
    toString() { console.log(this); } 
}

Or:

class ModeExtension {
    public toString = () => console.log(this);
}

enum Mode extends ModeExtension {
    landscape,
    portrait,
}

Of course the toString() function would contain something like a switch But a use-case would flow along the lines of:

class Device {
    constructor(public mode:Mode) {
        console.log(this.mode.toString());
    }
}

I understand why extending an enum might be a strange thing, just wondering if it is possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...