如何在打字稿中编写数组的函数 indexOf?
How to write in typescript the function indexOf for arrays?
我正在尝试将函数 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'.
为什么要处理一个类型包括=> boolean
。他在哪儿抱怨? never
类型是谁? batches
? batch
?
我感觉问题出在 batches
对象上,在提供程序中我没有使用类型,但 Typescript 没有抱怨这个对象。
内置数组方法indexOf
不将回调作为其参数,它需要在数组中查找一个元素。如果该元素包含在数组中,它将 return 该元素的第一个索引,如果该元素不在数组中,它将 return -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
的参数被推断为 "a member of the array: []"。由于没有空数组的成员,所以类型被推断为never
。有人肯定知道吗?
我正在尝试将函数 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'.
为什么要处理一个类型包括=> boolean
。他在哪儿抱怨? never
类型是谁? batches
? batch
?
我感觉问题出在 batches
对象上,在提供程序中我没有使用类型,但 Typescript 没有抱怨这个对象。
内置数组方法indexOf
不将回调作为其参数,它需要在数组中查找一个元素。如果该元素包含在数组中,它将 return 该元素的第一个索引,如果该元素不在数组中,它将 return -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
的参数被推断为 "a member of the array: []"。由于没有空数组的成员,所以类型被推断为never
。有人肯定知道吗?