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.
You can use extension methods to add functionality specific to a particular enum type.
C# Does not allow use of methods in enumerators as it is not a class based principle, but rather an 2 dimensional array with a string and value.
Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.
The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With