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:
Argument expression expected.(1135)
With any
obviously everything is alright:
private getRandomElementOfEnum(e : any):string{
var length:number = Object.keys(e).length;
return e[Math.floor((Math.random() * length)+1)];
}
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
ande[dynamicKey]
. For dynamic codes, the typeany
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:
Ideally, the parameter type
any
should be replaced bytypeof E
but the compiler (TS 1.5) can't understand this syntax.