Typescript has unions, so are enums redundant?

后端 未结 5 1750
闹比i
闹比i 2020-12-01 00:22

Ever since TypeScript introduced unions types, I wonder if there is any reason to declare an enum type. Consider the following enum type declaration:

enum X          


        
5条回答
  •  一整个雨季
    2020-12-01 01:23

    The enum type is not redundant, but in most cases union is preferred.

    But not always. Using enums to represents e.g state transitions could be much more handy and expressive than using union**

    Consider real live scenario:

    enum OperationStatus {
      NEW = 1,
      PROCESSING = 2,
      COMPLETED = 4
    }
    
    OperationStatus.PROCESSING > OperationStatus.NEW // true
    OperationStatus.PROCESSING > OperationStatus.COMPLETED // false
    

提交回复
热议问题