我正在使用 Typescript 编写一段代码,并遇到了以下问题,我无法理解为什么会发生这种情况。
下面的代码块Argument of type 'string | number' is not assignable to parameter of type 'never'
在编译时触发错误。
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))
Run Code Online (Sandbox Code Playgroud)
然而; (number | string)[]
如果我在声明/分配时使用b
,它工作得很好。
includes
我检查了( )的定义文件Array<T>.includes(searchElement: never, ...
,但这也没有意义,因为我认为泛型T
将包含number[] | string[]
.
如果有人能解释为什么Array<T>
不覆盖number[] | string[]
但覆盖,我将不胜感激(number | string)[]
。