what i'm trying to do is similar to this
enum Color
{
RED="RED",
GREEN="GREEN",
BLUE="BLUE"
}
function setColor(color:Color)
{
}
and when i want to call the function
setColor("RED"),
i get the error :
Argument of type '"RED"' is not assignable to parameter of type 'Color'.ts(2345),
i know i can use
setColor("Red" as Color)
,
but i want the RED to be autocompleted when i type, how can i do it ?
If you want to call your function setColor()
with a string literal argument (e. g. (setColor("RED")
) you should use a Union Type instead of an enum
.
type Color = "RED" | "Green" | "Blue";
declare function setColor(color: Color): unknown;
setColor("RED");
You can achieve this dynamically with your enum by using keyof typeof Color
.
enum Color {
RED = "RED",
GREEN = "GREEN",
BLUE = "BLUE"
}
declare function setColor(color: keyof typeof Color): unknown;
setColor("RED");