mrseanbaines
mrseanbaines

Reputation: 833

Why does TypeScript throw an error when searching for a string in an array with .includes?

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?

Upvotes: 0

Views: 1001

Answers (2)

Evert
Evert

Reputation: 99533

string is a broader type than Item, and when an array is typed with Item, you must also pass an Item.

You have a few options:

  1. Change the argument to an Item, as inthedark122 suggested. This way your type system ensures that you can't even call isInArray without a sane type.
  2. Use arr.includes(str as any). You're basically saying, 'I know what I'm doing'.
  3. In your function, first check if str is an Item, maybe with a type guard function. If str is not an item, you don't even have to use .includes() because if str is something else, you already know that it's not going to appear in the array.

Upvotes: 1

inthedark122
inthedark122

Reputation: 104

Typescript want that str should also be Item const isInArray = (str: Item) => {

Upvotes: 0

Related Questions