Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add description attribute to enum and read this description in TypeScript

I’m wondering how to add description attributes to enum in TypeScript. I would like to create enum as follows(or something similar):

public enum Sample
{
    [Display(Name = "Blah V")]
    V,

    [Display(Name = " Blah IV")]
    IV,

    [Display(Name = " Blah III")]
    III,
}

To be able to do basic operations on such enum I would create generic EnumHelper. This helper class should contain methods which allow: getting a description value, getting the name and numeric value. The question is how to achieve this in typescript? If it is not possible to add attributes to the enum, is there any way around? I would like to be able to:

-  get number of enum value,
-  get description value,
-  get the name of enum field.

e.g. for Sample.IV it would be:

1, 
Blah IV, 
IV.
like image 539
GoldenAge Avatar asked Jun 10 '18 13:06

GoldenAge


People also ask

Can I use enum as a type in TypeScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Can we define enum inside a class 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.

What is enum description?

An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: C# Copy.


1 Answers

Another interesting solution founded here is using ES6 Map:

export enum Sample {
  V,
  IV,
  III
}

export const SampleLabel = new Map<number, string>([
  [Sample.V, 'FIVE'],
  [Sample.IV, 'FOUR'],
  [Sample.III, 'THREE']
]);

USE

console.log(SampleLabel.get(Sample.IV)); // FOUR
like image 185
manzapanza Avatar answered Sep 18 '22 08:09

manzapanza