Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Implicit number to enum cast

Why does the following compile in TypeScript?

enum xEnum {
  X1,X2
}

function test(x: xEnum) {
}

test(6);

Shouldn't it throw an error? IMHO this implicit cast is wrong here, no?

Here is the playground link.

like image 902
duedl0r Avatar asked Sep 10 '14 10:09

duedl0r


People also ask

How to cast enum to string TypeScript?

To convert a numeric enum to a string, use bracket notation to access a specific value on the enum to get its name, e.g. NumericEnum[NumericEnum. Yes] . Similarly, you can convert a string enum to string, by using dot notation to access a specific property.

How do you convert a string value to a specific enum type in C#?

TryParse() method converts the string representation of enum member name or numeric value to an equivalent enum object. The Enum. TryParse() method returns a boolean to indicate whether the specified string is converted to enum or not. Returns true if the conversion succeeded; otherwise, returns false .

Is not assignable to type enum?

The error "Type string is not assignable to type Enum" occurs when we try to use a string literal in the place of an enum value. To solve the error, use dot or bracket notation to access the specific enum property or use a type assertion.

What is an enum TypeScript?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.


2 Answers

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

Enum types are assignable to the Number primitive type, and vice versa, but different enum types are not assignable to each other

So the decision to allow implicit conversion between number and Enum and vice-versa is deliberate.

This means you will need to ensure the value is valid.

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

Although you might not agree with the implementation, it is worth noting that enums 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 enum type you can use to guarantee you pick one that exists.

like image 160
Fenton Avatar answered Oct 14 '22 15:10

Fenton


No, it shouldn't. There is no type casting here, the base type behind them all is the same, integer.

typescript enum type checking works fine

Your complaint is about range value 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)
like image 2
itmitica Avatar answered Oct 14 '22 15:10

itmitica