Reputation: 833
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
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:
Item
, as inthedark122 suggested. This way your type system ensures that you can't even call isInArray
without a sane type.arr.includes(str as any)
. You're basically saying, 'I know what I'm doing'.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
Reputation: 104
Typescript want that str should also be Item const isInArray = (str: Item) => {
Upvotes: 0