Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
814 views
in Technique[技术] by (71.8m points)

casting - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...