如何在typescript中编写数组的函数indexOf



我正在尝试将函数arr.indexOf与Typescript:一起使用

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: []
}

我在useState挂钩中使用这个initState

const[level,setLevel]=useState(initState(

在我的组件中,我在level对象中使用batches

我得到的错误如下:

TS2345: Argument of type '(batch: BatchType) => boolean' is not assignable to parameter of type 'never'.

为什么治疗包括CCD_ 8在内的类型。他在哪里抱怨?never型是谁?batchesbatch

我觉得问题来自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

所以typescript抱怨你给indexOf一个类型错误的参数:你给它一个类型为(batch: BatchType) => boolean的谓词。

我不完全确定never,但由于typescript试图推断类型,我的猜测是indexOf的参数被推断为"数组的一个成员:[]"。由于没有空数组的成员,因此类型被推断为never。有人肯定知道吗?

最新更新