Alternatives to enums in TypeScript
BRANK

A recent blog post explored how TypeScript enums work. In this blog post, we take a look at alternatives to enums.Table of contents:Unions of singleton values  Unions of string literal types  Unions of symbol singleton types  Type unions vs. enums  Discriminated unions  Step 1: the syntax tree as a class hierarchy  Step 2: the syntax tree as a type union of classes  Step 3: the syntax tree as a discriminated union  Discriminated type unions vs. normal type unions  Object literals as enums  Object literals with string-valued properties  Upsides and downsides of using object literals as enums  Enum pattern  Summary of enums and enum alternatives  Acknowledgement  Further reading  Unions of singleton values  An alternative to creating an enum that maps keys to values, is to create a union of singleton types (one per value). Read on to see how that works.Unions of string literal types  Let’s start with an enum and convert it to a union of string literal types.enum NoYesEnum { No = 'No'…

2ality.com
Related Topics: TypeScript