如何在打字稿中为数组编写indexOf函数?

问题描述 投票:0回答:1

我正在尝试将函数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类型? batchesbatch

[我感觉问题出在batches对象,在提供程序中我没有使用类型,但是Typescript没有抱怨该对象。

reactjs typescript indexof
1个回答
1
投票

内置数组方法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。有人肯定知道吗?

© www.soinside.com 2019 - 2024. All rights reserved.