Add functions to an Enum
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);
Convert your enum
to the enum pattern. I find this is a better practice in general for many languages, since otherwise you restrict encapsulation options for your type. The tendency is to switch
on the enum value, when really any data or functionality that is dependent on the particular enum value should just go into each instance of the enum. I've added some more code to demonstrate.
This might not work if you are particularly dependent on the underlying enum values. In that case you would need to add a member for the old values and convert places that need it to use the new property.
class Mode {
public static landscape = new Mode(1920, 1080);
public static portrait = new Mode(1080, 1920);
public get Width(): number { return this.mWidth; }
public get Height(): number { return this.mHeight; }
// private constructor if possible in a future version of TS
constructor(
private mWidth: number,
private mHeight: number
) {
}
public GetAspectRatio() {
return this.mWidth / this.mHeight;
}
}
You can get the string value of an non-const enum by using square brackets:
class Device {
constructor(public mode:Mode) {
console.log(Mode[this.mode]);
}
}
You can also put some enum-specific util functions into the enum, but that's just like static class members:
enum Mode {
landscape,
portrait
}
namespace Mode {
export function doSomething(mode:Mode) {
// your code here
}
}