Here I am once again, looking for some advice on working with Typescript heuristics. I am facing challenges when trying to write a type guard because Typescript seems to be too restrictive when it comes to comparisons.
Let's consider the following scenario (or check out the Typescript Playground):
const FOO = 'foo' as const;
const BAR = 'bar' as const;
const ALL_THINGS = [FOO, BAR];
type AllThingsType = typeof ALL_THINGS[number];
function isAllThings(value: unknown): value is AllThingsType {
return typeof value === 'string' && ALL_THINGS.includes(value);
}
The error message you will encounter is:
Argument of type 'string' is not assignable to parameter of type '"foo" | "bar"'.ts(2345)
There is a workaround available:
function isAllThingsWorkaround(value: unknown): value is AllThingsType {
return typeof value === 'string' && (ALL_THINGS as string[]).includes(value);
}
Is there something that I might be missing in how I should approach this? The code snippet provided is a simplified version, but imagine if ALL_THINGS
actually consisted of nearly 25 constants. How can I enhance this without resorting to the workaround?
Thank you for your assistance!