Typescript has alliances, so are excess ones listed?

Since TypeScript introduced union types, I wonder if there is a reason to declare an enumeration type. Consider the following enumeration type declaration:

enum X { A, B, C } var x:X = XA; 

and a similar union type declaration:

 type X: "A" | "B" | "C" var x:X = "A"; 

If they basically serve the same purpose, and the unions are more powerful and expressive, then why do we need transfers?

+18
source share
3 answers

As far as I can see, they are not redundant, for the simple reason that union types are just a compile-time concept, whereas enums are actually wrapped and ended in the resulting javascript ( sample ).

This allows you to do some things with enumerations that are otherwise not possible with union types (for example, listing the possible enumeration values )

+12
source

There are several reasons why you can use enum

I see the great advantages of using union in that they provide a concise way of representing values โ€‹โ€‹by several types, and they are very readable. let x: number | string

EDIT: Starting with TypeScript 2.4 Enums now supports strings.

 enum Colors { Red = "RED", Green = "GREEN", Blue = "BLUE", } 
+7
source

Enumerations can conceptually be considered as a subset of union types allocated for values โ€‹โ€‹of type int and / or string , with some additional functions mentioned in other answers that make them convenient to use.

But the listings are not entirely safe:

 enum Colors { Red, Green, Blue } const c: Colors = 100; // No errors! type Color = | 0 | 'Red' | 1 | 'Green' | 2 | 'Blue'; const c2: Color = 100; // Error: Type '100' is not assignable to type 'Color' 

Union types support heterogeneous data and structures, including polymorphism, for example:

 class RGB { constructor( readonly r: number, readonly g: number, readonly b: number) { } toHSL() { return new HSL(0, 0, 0); // Fake formula } } class HSL { constructor( readonly h: number, readonly s: number, readonly l: number) { } lighten() { return new HSL(this.h, this.s, this.l + 10); } } function lightenColor(c: RGB | HSL) { return (c instanceof RGB ? c.toHSL() : c).lighten(); } 

I tend to look at F # to see good modeling practices. A quote from F # is for fun and profit, which may be useful here:

In general, you should give preference to delimited types of joins rather than enums, unless you need to have an int (or string ) value associated with them.

0
source

Source: https://habr.com/ru/post/1011744/


All Articles