I have a function that takes a string and it is supposed to call another function that only accepts values of two enum.
How can I narrow down the string type to be a type compatible with an enum? I tried with object.values but typescript doesn't seem to like in in any way I try.
export enum A {
a = "a",
b = "b",
c = "c",
}
export enum X {
x = "x",
y = "y",
z = "z",
}
export const T = { ...A, ...X } as const;
function foo(t: string): X | A {
if (Object.values(X).includes(t as X)) {
return t
}
if(Object.values(A).includes(t)){
return t
}
return X.x
}
Of course I can write a type guard function, but that is just cheating to me as I have to manually take care that the function code is correct and that, effectively, it correctly narrows down the string to be in one of the enums. So this is what I want to avoid:
function isXorA (t: string): t is X | A {
if (Object.values(X).includes(t as X)) {
return true
}
if(Object.values(A).includes(t as A)){
return true
}
return false
}
function foo(t: string): X | A {
if(isXorA(t)){
return t
}
return X.x
}