Enum as Parameter in TypeScript

后端 未结 9 1787
故里飘歌
故里飘歌 2020-12-01 13:18

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.         


        
9条回答
  •  旧时难觅i
    2020-12-01 14:15

    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: any): E {
        var keys = Object.keys(e),
            index = Math.floor(Math.random() * keys.length),
            k = keys[index];
        if (typeof e[k] === 'number')
            return e[k];
        return parseInt(k, 10);
    }
    
    function display(a: Color) {
        console.log(a);
    }
    
    enum Color { Blue, Green };
    display(getRandomElementOfEnum(Color));
    

    Ideally, the parameter type any should be replaced by typeof E but the compiler (TS 1.5) can't understand this syntax.

提交回复
热议问题