0

In my list component, I need to keep an array of string for each element, they represent the array of checked(by a checkbox) to perform an action like deleting, and I want to pass the links "themes/:id" that are not always the index, they're the ID from MySQL, that's why the simpler algorithm from MUI page to get the index number array isn't enough for me. But in the indexOf(element) line typescript says "Argument of type 'string' is not assignable to parameter of type 'never'." Why indexOf needs a never type? And what I can do to work around this?

const [selected, setSelected] = React.useState<Array<string>| [] >([]);

 const selectHandler = (listId: string) => () => {
   const currentIndex = selected.indexOf(listId);
   const newSelected = [...selected];
   if (currentIndex === -1) {
      newSelected.push(element);
   } else {
      newSelected.splice(currentIndex, 1);
   }
    setSelected(newSelected);
 }

And the checkbox component some lines further, that also has an error "any cannot be assigned to never". The "value._links.self.href" comes from spring data rest that returns this kind of JSON.

<Checkbox
  edge='end'
  onChange={selectHandler(value._links.self.href)}
  checked={checked.indexOf(value._links.self.href) !== -1}
  inputProps={{ 'aria-labelledby': labelId }}
/>
Raissa Correia
  • 169
  • 4
  • 18
  • The type `Array | []` is the issue, the second part of that produces the `never[]` type which is causing your problem. The easiest fix is just remove that ` | []` and let the state type just be `React.useState([])`. – CRice Sep 24 '21 at 17:25

1 Answers1

1

What is "not assignable to parameter of type never" error in typescript?

This question gave my the insight: Array my be correctly typed in this case

const [selected, setSelected] = React.useState<string[]>([]); 

and checkbox:

checked={selected.indexOf(value._links.self.href) !== -1}
Raissa Correia
  • 169
  • 4
  • 18