Enum as Parameter in TypeScript

后端 未结 9 1640
故里飘歌
故里飘歌 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条回答
  • 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>(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.

    0 讨论(0)
  • 2020-12-01 14:17

    @selinathat's solution is great only if you have few types. but what if we have more ? for example :

    doSomething(a: string, b: 'this'|'can'|'work'|'test1'|'test2'|'test3'): void {
     //do something
    }
    

    its pretty ugly hah !? i prefer to use keyof :

    interface Items {
        'this',
        'can',
        'work',
        'test1',
        'test2',
        'test3',
    }
    
    doSomething(a: string, b: keyof Items): void {
     //do something
    }
    
    0 讨论(0)
  • 2020-12-01 14:23

    Another possible option not mentioned above is using the actual values. This is however possible only when you know all the options. This, in my opinion is definitely better than any.

        doSomething(a: string, b: 'this'|'can'|'work'): void {
         //do something
        }
    
    0 讨论(0)
提交回复
热议问题