Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 298
Mr. Baudin Avatar asked Jan 26 '15 13:01

Mr. Baudin


People also ask

Can you add methods to enum?

You can use extension methods to add functionality specific to a particular enum type.

Can enum have functions C#?

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.

Can enum have functions in TypeScript?

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.

Can you put methods in an enum Java?

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.


1 Answers

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); 
like image 140
Fenton Avatar answered Oct 07 '22 07:10

Fenton