91

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.

5 Answers 5

116

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";
4
  • But is it possible to make encapsulated enums? Commented Nov 17, 2017 at 13:34
  • 3
    fabulous explanation!! Specially the one related to non-assigning of enum members.
    – shanti
    Commented Nov 29, 2018 at 7:15
  • 1
    The problem with your solution is, that you set the type of y to string and not to the actual type of the values of the FieldNames object which should be the one from @Martynas Skučas below. Here is the link: stackoverflow.com/a/59932722/1681085 Commented Feb 4, 2020 at 15:40
  • 1
    enum's behavior can be achieved using objects Commented Mar 14, 2023 at 7:44
36

I don't aggre with @Fenton. Objects are the type safe.

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

type ValueOf<T> = T[keyof T];
let y: ValueOf<typeof FieldNames>;

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

// TS2322: Type '"str"' is not assignable to type '"Field One" | "Field Two"'.
y = 'str';

// TS2540: Cannot assign to 'FirstField' because it is a read-only property
FieldNames.FirstField = 'str';
4
  • 5
    I like your thinking. Setting y to type string is not the best way. Very good answer in my opinion. However, it does not answer the whole question. Commented Feb 4, 2020 at 15:38
  • 6
    as const was introduced in TS 3.4 which was released in 2019. And the original answer from @Fenton was posted in 2017. I think this is a valid updated answer. Also in fact, the TS official docs now says that most of the time as const can work to replace enum.
    – coolgod
    Commented Jun 18, 2021 at 5:39
  • 2
    @coolgod can you point me where in the docs is the "as const will replace enum most of the time" is said? I could find it.
    – Edu Ruiz
    Commented Jul 29, 2021 at 15:10
  • 4
    @EduRuiz typescriptlang.org/docs/handbook/enums.html#objects-vs-enums
    – Robula
    Commented Sep 21, 2021 at 12:56
11
function (foo: FieldNames) { }

If FieldNames is an object, this means this function expects an instance which has the properties FirstField and SecondField. If FieldNames is an enum (in which case it should be singular, not plural), this means the function expects one of the values of FieldNames, namely "Field One" or "Field Two".

Very different usage.

6
  • But you can achieve that behaviour by just using interfaces and/or classes. Commented Nov 17, 2017 at 13:11
  • How do you easily define an interface or class that says "one of these values"?
    – deceze
    Commented Nov 17, 2017 at 13:12
  • An abstract class with static FieldName properties? Or something like that. Commented Nov 17, 2017 at 13:14
  • 2
    An enum as a type hint says "the variable may take one of the values in this list". An enum as an object makes those values easily accessible by something like constants (e.g. FieldName.FirstField); you can change the underlying value without needing to rewrite all the code that uses it. – That is all very different from classes/objects, in which you can instantiate an object from a class and pass that object around and type hint against the object type.
    – deceze
    Commented Nov 17, 2017 at 13:20
  • 2
    You can do function (foo: keyof FieldNames) { } instead Commented Feb 3, 2018 at 18:30
5

In the Typescript language handbook, you have a dedicated section talking about that: Objects vs Enums.

Personally, when I need a type with a set of options, I prefer using Typescript enum, because it is easier to use. With the enum definition, you have the type and also the way to access the options. To implement the same aproach with an object, you need to define the object as const and also define an extra type based on it.

1

this should be main reason.. you can use enum as a type so one of following options, but you cant define cosnt object as a type, it will have all options in one obj :)

you can also do this

type FieldNames = "Field One" | "Field Two";

but if list is long, enum is much better, in ES6 enum is pure useless just use obejct but in typescript its a type and its a main benefit in my opition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.