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?
unknown
type as argument? The function should return the enum value (if it exists), otherwise undefined. For example:let input : unknown = 'blue'; let result = getParam(color, input);
. (2) It is possible to return the typePartial<keyof typeof color>;
(in case of colors) andPartial<keyof typeof coverage>;
and so on? Of course only if the key exists, otherwise it should beundefined
. – Burkhardt