0

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?

2
  • It appears as though you already know why it is happening... Commented Mar 26, 2020 at 20:01
  • What does confuse me though is the fact that Array#includes is typed as includes(item: T) rather than includes(item: any), which seems silly. Commented Mar 26, 2020 at 20:45

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.