Reactjs 如何在typescript中编写数组的函数indexOf?
我正在尝试将函数Reactjs 如何在typescript中编写数组的函数indexOf?,reactjs,typescript,indexof,Reactjs,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 } 批处理来自上下文,没有类型: c
arr.indexOf
与Typescript一起使用:
const index: number = batches.indexOf((batch: BatchType) => (batch.id === selectedBatchId))
BatchType
是以下类型:
export default interface BatchType {
id: number,
month: number,
year: number
}
批处理
来自上下文,没有类型:
const initState = {
dance: {
id: '',
name: ''
},
level: {
id: '',
name: '',
schedule: ''
},
batches: []
}
我在useState
钩子中使用这个initState
:
const[level,setLevel]=useState(initState)
在我的组件中,我在级别
对象中使用批处理
我得到的错误如下:
TS2345: Argument of type '(batch: BatchType) => boolean' is not assignable to parameter of type 'never'.
为什么要处理包含=>布尔值的类型。他在哪里抱怨?谁是类型从不<代码>批次
<代码>批次
我感觉问题来自于批处理
对象,在提供程序中我没有使用类型,但Typescript没有抱怨这个对象。内置数组方法indexOf
没有将回调作为参数,它需要在数组中查找元素。如果元素包含在数组中,它将返回该元素的第一个索引,如果元素不在数组中,它将返回-1
发件人:
因此,typescript抱怨您给参数的索引类型错误:您给它的谓词类型为(batch:BatchType)=>boolean
我不完全确定从不
——但由于typescript试图推断类型,我猜测indexOf
的参数被推断为“数组的成员:[]。由于空数组中没有成员,因此该类型被推断为never
。有人知道这一点吗?我的错,我打开了两个docu,实际上解决方案是用findIndex方法。因为我在学习TS,所以我专注于TS的错误,而不是方法的错误。为这个错误道歉
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1