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.
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.
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.
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.
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
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