【发布时间】:2020-08-05 23:26:12
【问题描述】:
在 TypeScript 中,我定义了一个 enum,然后我想要一个函数接受一个参数,其值为枚举值之一。但是,TypeScript 似乎不对值进行任何验证,并允许枚举之外的值。有没有办法做到这一点?
示例
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
另类
如果我使用 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'
【问题讨论】:
-
您看过这个问题及其答案吗? stackoverflow.com/questions/43804805/…
-
@JonahBishop 显然我有,因为我已经对问题和答案进行了投票。 :) 这对我帮助不大。我可以在我的函数中添加一个条件,比如
if(!Object.values(myenum).includes(num)) throw('Illegal Argument');,但是当我宁愿它是打字稿可以在编译时识别的东西时,这会导致它成为运行时错误。
标签: typescript enums