Issue
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 typesafe.
Is there a possibility or a little workaround to define an enum as a parameter?
Solution
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.
Answered By - Paleo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.