TypeScript: implicit number to enumerate

Why is the next compilation in TypeScript?

enum xEnum { X1,X2 } function test(x: xEnum) { } test(6); 

Isn't that a mistake? IMHO, this implicit cast is wrong here, no?

Here is the playground link.

+6
source share
2 answers

This is part of the language specification (3.2.7 Enum Types):

Enumeration types are assigned to the primitive type Number and vice vice versa, but different types of enumerations cannot be assigned to each other

Thus, the decision to allow implicit conversion between number and Enum and vice versa will be intentional.

This means that you will need to make sure that the value is valid.

 function test(x: xEnum) { if (typeof xEnum[x] === 'undefined') { alert('Bad enum'); } console.log(x); } 

Although you may not agree with the implementation, it is worth noting that the enumerations are useful in these three situations:

 // 1. Enums are useful here: test(xEnum.X2); // 2. ...and here test(yEnum.X2); 

And 3. - when you type test( , it will tell you the type of enumeration that you can use to ensure that you select the one that exists.

+8
source

No, it should not. There is no type of casting here, the basic type behind them is all the same, integer.

typescript enum type checking works fine

Your complaint concerns the value of the range, which in this case has nothing to do with type checking.

enum is a flexible set of constants

 enum xEnum {X1=6, X2} // ruins it for test(0) 
+1
source

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


All Articles