B
B
BonBon Slick2021-07-02 16:28:41
typescript
BonBon Slick, 2021-07-02 16:28:41

When to use Enum and when to use Union?

https://stackoverflow.com/questions/18111657/how-t...
https://stackoverflow.com/questions/40275832/types...

export enum SocialAuthService {
    FACEBOOK = 'facebook',
    GOOGLE   = 'google',
}

type SocialAuthServiceType =
    | SocialAuthService.FACEBOOK
    | SocialAuthService.GOOGLE
    ;

someFunc(service: SocialAuthServiceType){
..
}

Playground

You can get identical functionality using both those and other language features (enam and union).
Other enum approaches are also described in CO, for example
const Permission = {
  Read: 'r',
  Write: 'w',
  Execute: 'x'
} as const;

Which begs the question, which approach is better then, and why?
Use enum or type? If enum, then which approach is better, class or enum?

When and how is it right, why so?
When to use union and when to use enum?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-07-02
@BonBonSlick

Union when only the type is needed, enum when the runtime values ​​are also needed. It's obvious. A const object is stupidly not as convenient as an enum, there is no point in it for this class of tasks.
In general, strictly speaking, enum should be used when enum is needed. L - logic. Enum - Enumeration - Enumeration. There is an enumeration - use enum.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question