In the following example code, TypeScript throws a Argument of type 'string' is not assignable to parameter of type 'Item'. ts(2345) error.
type Item = 'foo' | 'bar' | 'baz'
const isInArray = (str: string) => {
const arr: Item[] = ['foo', 'bar', 'baz']
return arr.includes(str)
^^^
}
I realise that I could remove the Item[] type from arr which would turn it into a string[] and prevent the error, however, in real-life where I ran into this, the array is the result of mapping through some array of objects which is typed, thus resulting in the array being typed accordingly.
I feel like this should work, since we know in advance what the values of the array are, but not necessarily what the input argument is.
I guess I'm missing something. Why is this error happening and how can I resolve it?