I am using several enums as global parameters.
enum color {
'red' = 'red',
'green' = 'green',
'blue' = 'blue',
};
enum coverage {
'none' = 'none',
'text' = 'text',
'background' = 'background',
};
I merge all enums to a type myEnums.
type myEnums = color | coverage;
Now I want to check and access values of the enums. For instance:
// Returns undefined if the argument value is not a color.
function getColor(value: string): color | undefined{
if(value in color) return value as color;
return undefined;
}
Because there are several enums, I want to create a generic function to access all of my enums. I tried the following:
function getParam<T extends myEnums>(value: string): T | undefined {
if(value in T) return value as T;
return undefined;
}
getParam<color>('red', color); // => should return 'red'
getParam<coverage>('test', coverage); // => should return undefined
But the Typescript compiler says: 'T' only refers to a type, but is beeing used as a value here.'.
So I added an argument list: T to the function, but then Typescript assums that the argument list has the type string (and not object).
The right-hand side of an 'in' expression must not be a primitive.
function getParam<T extends allEnums>(value: string, list: T): T | undefined {
if(value in list) return value as T;
return undefined;
}
So how can I call a generic function using T as an enum?