Enum as Parameter in TypeScript

后端 未结 9 1740
故里飘歌
故里飘歌 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:12

    Here is an example that allows passing an enum with a typechecked value of that enum using a generic. It's really a response to a slightly different question here that was marked as a duplicate: Typescript how to pass enum as Parameter

    enum Color {
        blue,
    };
    enum Car {
        cadillac,
    };
    enum Shape {
        square,
    }
    
    type SupportedEnums = typeof Color | typeof Car;
    
    type InvertTypeOf = T extends typeof Color ? Color :
        T extends typeof Car ? Car : never;
    
    function getText(enumValue: InvertTypeOf, typeEnum: T) string | undefined {
      if (typeEnum[enumValue]) {
        return `${enumValue}(${typeEnum[enumValue]})`;
      }
    }
    
    console.log(getText(Car.cadillac, Car)); // 0(cadillac)
    console.log(getText(0, Color)); // 0(red)
    console.log(getText(4, Color)); // undefined
    
    // @ts-expect-error Color is not Car
    console.log(getText(Color.blue, Car));
    
    // @ts-expect-error Car is not a Color
    console.log(getText(Car.toyota, Color));
    
    // @ts-expect-error  Shape is not in SupportedEnums
    console.log(getText(5, Shape));
    
    // @ts-expect-error  Shape is not in SupportedEnums
    console.log(getText(Shape.square, Shape));
    

提交回复
热议问题