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.
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));