I'm working on a piece of code in Typescript, and came across this below issue that I can't make much sense as to why it's happening.
The below code block triggers an Argument of type 'string | number' is not assignable to parameter of type 'never' error at compile.
interface A {
x: number | string
}
const a1: A[] = [{x: 1}, {x: 'a'}]
const b: number[] | string[] = ['a', 'b']
const a2 = a1.filter(a => b.includes(a.x))
However; if I were to use (number | string)[] when declaring/assigning b, it works fine.
I checked the definition file for includes (Array<T>.includes(searchElement: never, ...), but that also didn't make sense because I thought that the generic T would encompass number[] | string[].
I would appreciate if someone could shine a light as to why the Array<T> doesn't cover number[] | string[] but covers (number | string)[].
number[] | string[]is either an array of all numbers or an array of all strings.(number | string)[]is an array of elements each of which may either be a number or a string. Any array that meets the first definition will meet the second, but the opposite is not true.a.xbe comparable to each element ofb? Because it's not like a singlestringtonumbercomparison of which the result would always be false.