DEV Community

Discussion on: TypeScript Enums: 5 Real-World Use Cases

Collapse
 
alexefimenko profile image
Alex • Edited

Great advice, thanks!
Object like

const loadingState = {
  Idle: 'idle',
  Loading: 'loading',
  Success: 'success',
  Error: 'error',
} as const
Enter fullscreen mode Exit fullscreen mode

can work the same way as enums.
Could you mention the use cases where this approach is better?

Collapse
 
sunpietro profile image
Piotr Nalepa

You can change it to: const enum loadingState and it will work the same without being smarter giving as const at the end.

Collapse
 
cristobalgvera profile image
Cristóbal Gajardo Vera • Edited

When working with Angular, if you define an enum to be used as an input property, it willl require you to assign that enum to a class attribute of the parent component and later use it in the html template, else you simply can't us it. An this is just an example.

In that case, a map using as const and also keyof typeof will let you to use the typed string in the html.

The approach that unify the definition for enum and let you use it as is, is the following:

const MyEnum = {
  FIRST: 'First',
  SECOND: 'Second',
} as const;

type MyEnum = (typeof MyEnum)[keyof typeof MyEnum];
      // ^? type MyEnum = "First" | "Second"

declare function func(a: MyEnum): void;

func(MyEnum.FIRST); // Valid
func('First'); // Valid
Enter fullscreen mode Exit fullscreen mode

The real problem is that TypeScript doesn't recognize an enum as a string, even if the enum values are all strings. This aspect of enum make them "weird" in constrast of as const objects.

enum MyEnum {
  FIRST = 'First',
  SECOND = 'Second',
};

declare function func(a: MyEnum): void;

func(MyEnum.FIRST); // Valid
func('First'); // Invalid
Enter fullscreen mode Exit fullscreen mode

A better explanation: dev.to/muszynov/something-about-ty...