枚举作为 TypeScript 中的参数 [英] Enum as Parameter in TypeScript
问题描述
不能将参数的类型设置为枚举吗?像这样:
private getRandomElementOfEnum(e : enum):string{var length:number = Object.keys(e).length;返回 e[Math.floor((Math.random() * length)+1)];}
编译抛出以下错误:
<块引用>需要参数表达式.(1135)
使用 any
显然一切正常:
private getRandomElementOfEnum(e : any):string{var length:number = Object.keys(e).length;返回 e[Math.floor((Math.random() * length)+1)];}
此代码工作正常.但没有那么优雅和代码约定.
是否有可能或一些解决方法将枚举定义为参数?
无法确保参数是枚举,因为 TS 中的枚举不从共同的祖先或接口继承.
TypeScript 带来静态分析.您的代码使用带有 Object.keys
和 e[dynamicKey]
的动态编程.对于动态代码,any
类型很方便.
您的代码有问题:length()
不存在,e[Math.floor((Math.random() * length)+1)]
返回字符串或整数,枚举值可以手动设置...>
这是一个建议:
function getRandomElementOfEnum(e: any): E {var 键 = Object.keys(e),index = Math.floor(Math.random() * keys.length),k = 键[索引];if (typeof e[k] === '数字')返回<any>e[k];返回 <any>parseInt(k, 10);}功能显示(a:颜色){控制台日志(一);}枚举颜色{蓝色,绿色};显示(getRandomElementOfEnum<颜色>(颜色));
理想情况下,参数类型 any
应替换为 typeof E
但编译器 (TS 1.5) 无法理解此语法.
Isn't it possible to set the type of a parameter to an Enum? Like this:
private getRandomElementOfEnum(e : enum):string{
var length:number = Object.keys(e).length;
return e[Math.floor((Math.random() * length)+1)];
}
Following error is thrown by compilation:
Argument expression expected.(1135)
With any
obviously everyhting is alright:
private getRandomElementOfEnum(e : any):string{
var length:number = Object.keys(e).length;
return e[Math.floor((Math.random() * length)+1)];
}
This Code works fine. but isn't as elegant and code-convential.
Is there a possibility or a little workaround to define an enum as a parameter?
It's not possible to ensure the parameter is an enum, because enumerations in TS don't inherit from a common ancestor or interface.
TypeScript brings static analysis. Your code uses dynamic programming with Object.keys
and e[dynamicKey]
. For dynamic codes, the type any
is convenient.
Your code is buggy: length()
doesn't exists, e[Math.floor((Math.random() * length)+1)]
returns a string or an integer, and the enumeration values can be manually set…
Here is a suggestion:
function getRandomElementOfEnum<E>(e: any): E {
var keys = Object.keys(e),
index = Math.floor(Math.random() * keys.length),
k = keys[index];
if (typeof e[k] === 'number')
return <any>e[k];
return <any>parseInt(k, 10);
}
function display(a: Color) {
console.log(a);
}
enum Color { Blue, Green };
display(getRandomElementOfEnum<Color>(Color));
Ideally, the parameter type any
should be replaced by typeof E
but the compiler (TS 1.5) can't understand this syntax.
这篇关于枚举作为 TypeScript 中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!