AlbertMunichMar
AlbertMunichMar

Reputation: 1866

How to write in typescript the function indexOf for arrays?

I am trying to use the function arr.indexOf with Typescript:

const index: number = batches.indexOf((batch: BatchType) => (batch.id === selectedBatchId))

BatchType is following type:

export default interface BatchType {
  id: number,
  month: number,
  year: number
}

batches are coming from a context, without types:

const initState = {
  dance: {
    id: '',
    name: ''
  },
  level: {
    id: '',
    name: '',
    schedule: ''
  },
  batches: []
}

I use this initState in the useState hook:

const [level, setLevel] = useState(initState)

In my component, I use the batches within the level object.

The error that I get is the following:

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

Why is treating a type including the => boolean. Where is he complaining? Who is type never? batches? batch?

I had the feeling that the problem comes from the batches object, that in the provider I am not using types, but Typescript is not complaining for this object.

Upvotes: 0

Views: 1572

Answers (1)

abekonge
abekonge

Reputation: 126

The built in array-method indexOf does not take a callback as its argument, it takes an element to look for in the array. If the element is contained in the array, it will return the first index of that element, if the element is not in the array, it will return -1.

From 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

So typescript is complaining that you are giving indexOf an argument with a wrong type: you are giving it a predicate with the type (batch: BatchType) => boolean.

I'm not totally sure about never - but since typescript is trying to infer types, my guess is that the argument to indexOf is inferred to be "a member of the array: []". Since there is no member of an empty array, the type is inferred to be never. Anyone know this for sure?

Upvotes: 1

Related Questions