简体   繁体   English

Typescript 枚举作为参数类型允许无效值

[英]Typescript enum as a parameter type allows invalid values

In TypeScript, I'm defining an enum , then I want a function to take a parameter whose value is one of the enum's values.在 TypeScript 中,我定义了一个enum ,然后我想要一个 function 采用一个参数,其值为枚举值之一。 However, TypeScript doesn't seem to do any validation on the value, and allows values outside of the enum.但是,TypeScript 似乎没有对值进行任何验证,并允许枚举之外的值。 Is there a way to do this?有没有办法做到这一点?

Example例子

enum myenum {
    hello = 1,
    world = 2,
}

const myfunc = (num:myenum):void => console.log(`num=${num}`);

myfunc(1);            // num=1 (expected)
myfunc(myenum.hello); // num=1 (expected)

//THE ISSUE: I'm expecting next line to be a TS compile error, but it is not
myfunc(7); // num=7

Alternative选择

If I use a type instead of enum I can get something similar to what I'm looking for, but I lose some of the functionality of enum.如果我使用type而不是enum ,我可以获得类似于我正在寻找的东西,但我失去了枚举的一些功能。

type mytype = 1|2;
const myfunc = (num:mytype):void => console.log(`num=${num}`);

myfunc(1);
myfunc(7);  //TS Compile Error: Argument of type '7' is not assignable to a parameter of type 'mytype'

Update更新

Seems, as of now, this is working as designed .看来,到目前为止,这正在按设计工作

you might be expecting too much from enum in TS... :)您可能对 TS 中的枚举期望过高... :)

enum MyCoolEnum {
  A = 1,
  B = 2,
}

function test(data: MyCoolEnum) {
  console.log(`Test = ${typeof data}`)
}

test(1)
test(MyCoolEnum.A)
test(500)

If you run this code above, you will see that all the lines print number that means that behind the scenes it is translated to a number and that's why it accepts everything... Enums are usually just a good practice to avoid magic numbers and make the code more readable如果您在上面运行此代码,您将看到所有行都打印number ,这意味着在幕后它被转换为数字,这就是它接受所有内容的原因......枚举通常只是避免幻数并制作的一个好习惯代码更具可读性

On the other hand, if you stop using numeric enums and actually change the values for A and B to strings you will get:另一方面,如果您停止使用数字枚举并实际将 A 和 B 的值更改为字符串,您将获得:

TSError: ⨯ Unable to compile TypeScript:
dima.ts:10:6 - error TS2345: Argument of type '1' is not assignable to parameter of type 'MyCoolEnum'.

10 test(1)
        ~
dima.ts:12:6 - error TS2345: Argument of type '500' is not assignable to parameter of type 'MyCoolEnum'.

12 test(500)
        ~~~

    at createTSError (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:423:12)
    at reportTSError (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:427:19)
    at getOutput (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:554:36)
    at Object.compile (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:760:32)
    at Module.m._compile (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:839:43)
    at Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:842:12)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)

So what I'm trying to say is that if it's a numeric enum it's just cosmetics and it's treated as a number but if you make a string enum for example then it's actually tries to match the type所以我想说的是,如果它是一个数字枚举,它只是化妆品,它被视为一个数字,但如果你制作一个字符串枚举,那么它实际上是在尝试匹配类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM