I want to narrow a string to a string literal union. In other words, I want to check if the string is one of the possible values of my literal union, so that this will work (if the operator couldbe
existed).
type lit = "A" | "B" | "C";
let uni: lit;
let str = "B";
if(str couldbe lit){
uni = str;
} else {
doSomething(str);
}
How can I achieve this?
I tried using if (str instanceof lit)
, but that doesn't seem to work. Using keyof
to iterate over the string union doesn't work either, because the allowed values aren't keys per se.
One way would be to use switch
with one case for each possible value, but that could lead to subtle errors if lit
s allowed values change.
lit
doesn't exist at runtime so you cannot use it like that. Maybe use an enum instead? – Front