Enum as Parameter in TypeScript

后端 未结 9 1781
故里飘歌
故里飘歌 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 13:59

    Summing up the previous answers with some new syntax - a generic typesafe function, which works with numeric enums as well as string enums:

    function getRandomElementOfEnum(e: T): T[keyof T] {
      const keys = Object.keys(e);
    
      const randomKeyIndex = Math.floor(Math.random() * keys.length);
      const randomKey = keys[randomKeyIndex];
    
      // Numeric enums members also get a reverse mapping from enum values to enum names.
      // So, if a key is a number, actually it's a value of a numeric enum.
      // see https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
      const randomKeyNumber = Number(randomKey);
      return isNaN(randomKeyNumber)
        ? e[randomKey as keyof T]
        : randomKeyNumber as unknown as T[keyof T];
    }
    

提交回复
热议问题