TypeScript: Implicit number to enum cast

后端 未结 2 1365
野性不改
野性不改 2020-12-11 16:23

Why does the following compile in TypeScript?

enum xEnum {
  X1,X2
}

function test(x: xEnum) {
}

test(6);

Shouldn\'t it throw an error? I

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 16:52

    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.

提交回复
热议问题