I should be allowed to pass anything into Array.includes
to check if it's in the array, but TypeScript doesn't want me to pass in something that isn't the right type. For instance:
type Fruit = "apple" | "orange";
type Food = Fruit | "potato";
const fruits: Fruit[] = ["apple", "orange"];
function isFruit(thing: Food) {
return fruits.includes(thing); // ts error: "potato" is not assignable to type 'Fruit'.
}
What is a clean way to fix this code with minimal impact on readability?
I ended up doing this (seems no drawback):
function isFruit(thing: Food) {
return (fruits as Food[]).includes(thing);
}