Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  85] [ 4]  / answers: 1 / hits: 32148  / 7 Years ago, fri, november 17, 2017, 12:00:00

I am trying to access values of a map via enum and also make a translation ready app for all the strings in it.
Both concerns overlap and I have to decide between using enums or just object in JSON format.



So what exactly is the difference and useage between an enum and an object?



For example:




  • I can use enums to access arrays as well as inserting labels and other stuff like





const enum FieldNames {
FirstField: Field One,
SecondField: Field Two
};

someFieldArray[FieldNames.FirstField].label = FieldNames.FirstField;
someFieldArray[FieldNames.SecondField].label = FieldNames.SecondField;






  • Or I can achieve the same behaviour via object





const FieldNames = {
FirstField: Field One,
SecondField: Field Two
};

someFieldArray[FieldNames.FirstField].label = FieldNames.FirstField;
someFieldArray[FieldNames.SecondField].label = FieldNames.SecondField;





I really do not get the benefit choosing enums over simple objects. In my opinion an object has much more benefits without any downsides.


More From » typescript

 Answers
16

Enum



An enum may give you additional benefits, if you want the features:



const enum FieldNamesEnum {
FirstField = Field One,
SecondField = Field Two
};

let x: FieldNamesEnum;

x = FieldNamesEnum.FirstField;
x = FieldNamesEnum.SecondField;

// Error - not assignable to FieldNames
x = 'str';

// Cannot assign
FieldNamesEnum.FirstField = 'str';


Importantly, you can't assign to the enum members and types are checked to the enum members, rather than string.



Additionally, because you have used a const enum in your example, the enum won't exist at runtime and all the references will be substituted for the literal values (if you used a plain enum the enum would exist at runtime).



Object



Compare this to the object example:



const FieldNames = {
FirstField: Field One,
SecondField: Field Two
};

let y: string;

y = FieldNames.FirstField;
y = FieldNames.SecondField;

// Oops it works
y = 'str';

// Oops it works

FieldNames.FirstField = 'str';


Union



If you don't need the full enum, but want to limit the values, you can use a union of literal values:



type FieldNames = Field One | Field Two;

let x: FieldNames;

x = Field One;
x = Field Two;

// Error - not allowed
x = Field Three;

[#55908] Tuesday, November 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
malkajillc

Total Points: 652
Total Questions: 107
Total Answers: 98

Location: Finland
Member since Sat, Nov 6, 2021
3 Years ago
malkajillc questions
;