Enums vs Constant differences on Typescript

I agree with @VLAZ, the best approach can definitely vary. Probably the most significant perk of using an enum is being able to improve type-safety of your functions.

export enum LocalStorage {
    USER_INFO = "user-info",
    PROFILE_INFO = "profile-info"
} 

function doSomething(l: LocalStorage) {
}

doSomething("foo"); // error, "foo" is not LocalStorage
doSomething("user-info"); // error, "user-info" is not LocalStorage
doSomething(LocalStorage.USER_INFO); // compiles

Overall, enums offer improved type safety (where they make sense), and extending them with new members is generally simpler.


While both approaches get the job done for simple scenarios. It's always good practice to use constructs for their intended purposes.

Your class may inadvertently evolve into something more than just holding statics. Leading to an amalgamation of concerns. For instance, in the future you may think it necessary to add CRUD functions for local storage, indexedDB, or cookies.

Then the question comes to using const enums or just enums.

If you need the compiled enum at run time, then use a regular TS enum. Otherwise, a const enum exists just to help with type-safety, less generated code, and minimised access indirection but without run-time lookup values.


enum is logical grouping of your constants. Let's say you want to use different color. Then you make color enum consist of all colors value defined. Lets say accountType which consist value of current, saving, loan, recurring. Its logical grouping. Constant you can define for anything.

Now you have to make sure that your enum name has anything to do with logical grouping?

In Your case Enum name is LocalStorage but values underneath does not justify as enum