I am facing an issue with the following array declaration:
// Using const as I require it to be a specific type elsewhere
const fruits = ["strawberry", "banana", "orange", "grapefruit"] as const;
When attempting to check if an unknown value (possibly from an HTTP controller) exists in the array, like this:
const input: string = SomeRandomService.getMyString();
if(!fruits.includes(input)) {
throw new Error("Not present");
}
This results in the error message regarding .includes(input)
:
TS2345: Argument of type 'string' is not assignable to parameter of type '"strawberry" | "banana" | "orange" | "grapefruit"'.
I do not understand why this error occurs. The code seems valid to me, as my intention is to ensure that the value is indeed one of those present in the array. How can I resolve this issue without resorting to using input as any
)?