我有一个像这样定义的枚举
export enum someEnum {
None = <any>'',
value1 = <any>'value1',
value2 = <any>'value2',
value3 = <any>'value3'
}
Run Code Online (Sandbox Code Playgroud)
例如,我想检查枚举中是否存在"value4".我应该得到错误,因为在枚举中没有定义value4.
我尝试if (someEnum['value4'])但是得到错误 - 元素隐式具有"任何"类型,因为索引表达式不是"数字"类型.
在 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
Run Code Online (Sandbox Code Playgroud)
如果我使用 atype而不是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 …Run Code Online (Sandbox Code Playgroud) 例如
enum ABC { A = "a", B = "bb", C = "ccc" };
alert("B" in ABC); // true
alert("bb" in ABC); // false (i wanna true)
Run Code Online (Sandbox Code Playgroud)
请记住,我们讨论字符串枚举功能.