我正在尝试将函数arr.indexOf
与打字稿一起使用:
const index: number = batches.indexOf((batch: BatchType) => (batch.id === selectedBatchId))
BatchType
是以下类型:
export default interface BatchType {
id: number,
month: number,
year: number
}
batches
来自上下文,没有类型:
const initState = {
dance: {
id: '',
name: ''
},
level: {
id: '',
name: '',
schedule: ''
},
batches: []
}
我在initState
钩子中使用此useState
:
const [level,setLevel] = useState(initState)
在组件中,我使用batches
对象中的level
。
我得到的错误如下:
TS2345: Argument of type '(batch: BatchType) => boolean' is not assignable to parameter of type 'never'.
为什么处理包含=> boolean
的类型。他在哪里抱怨?谁是never
类型? batches
? batch
?
[我感觉问题出在batches
对象,在提供程序中我没有使用类型,但是Typescript没有抱怨该对象。
内置数组方法indexOf
不会将回调作为其参数,它需要在数组中查找一个元素。如果该元素包含在数组中,则将返回该元素的第一个索引;如果该元素不在数组中,则将返回-1。
来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf:
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
所以打字稿抱怨您给indexOf一个类型错误的参数:您给它一个谓词(batch: BatchType) => boolean
类型。
我不确定never
-但是由于打字稿正在尝试推断类型,因此我猜测是indexOf
的参数被推断为“数组的成员:[]”。由于没有空数组的成员,因此类型推断为never
。有人肯定知道吗?