我正在尝试将函数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
型是谁?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
所以typescript抱怨你给indexOf一个类型错误的参数:你给它一个类型为(batch: BatchType) => boolean
的谓词。
我不完全确定never
,但由于typescript试图推断类型,我的猜测是indexOf
的参数被推断为"数组的一个成员:[]"。由于没有空数组的成员,因此类型被推断为never
。有人肯定知道吗?