Property 'filter' does not exist on type 'Setstateaction<Never[]>'

Asked

Viewed 243 times

-1

I’m having trouble getting this little piece of code to work: inserir a descrição da imagem aqui

Here is my code:

import React, {SetStateAction} from 'react';
import {BsCheck, BsTrashFill} from 'react-icons/bs';

type Props = {
  text: string,
  todos: SetStateAction<never[]>,
  setTodos: React.Dispatch<React.SetStateAction<never[]>>
}

const Todo: React.FC<Props> = ({text, todos, setTodos}) => {
  const deleteHandler = () => {
    setTodos(todos.filter(el => el.id !== todos.id))
  }

  return(
    <div className="todo">
      <li className="todo-item">{text}</li>
      <BsCheck className="check" size={35}/>
      <BsTrashFill onClick={deleteHandler} className="trash" size={35}/>
    </div>
  );
}

export default Todo;

The mistakes are:

Property 'filter' does not exist on type 'Setstateaction<Never[]>'.
Property 'filter' does not exist on type '(prevState: Never[]) => Never[]'.

Parameter 'el' implicitly has an 'any' type.

Property 'id' does not exist on type 'Setstateaction<Never[]>'.
Property 'id' does not exist on type 'Never[]'.

  • 1

    You know what the guy is never? It doesn’t make much sense to use it there...

  • 1

    as commented by @Luizfelipe, since the type was used never, must not be dealing with a valid array, so the filter cannot be used

1 answer

0

You can just write it down using any[]:

type Props = {
  text: string,
  todos: any[],
  setTodos: (todos: any[]) => void
}

Or you can write interface ITodo as:

interface ITodo {
  id: number
  name: string
  // ..
}

type Props = {
  text: string,
  todos: ITodo[],
  setTodos: (todos: ITodo[]) => void
}

Because, in React, Dispatch is defined as:

type Dispatch<A> = (value: A) => void; // Function

And SetStateAction:

type SetStateAction<S> = S | ((prevState: S) => S); // Function Ou Value

And you need to idToDelete thus:

const deleteHandler = (idToDelete) => {
  setTodos(todos.filter(el => el.id !== idToDelete))
}
  • 2

    I think it is worth explaining also why the AP code does not work. Often, including, use any is not ideal, because it nullifies a number of benefits that make the person go to Typescript in the first place.

  • 1

    @Luizfelipe Ok, I’ll write about it. Thank you :)

  • Now I have this error: Property 'all' is Missing in type '{ setTodos: (all: Itodo[]) => void; key: number; text: string; }' but required in type 'Props'. I don’t think it worked very well

Browser other questions tagged

You are not signed in. Login or sign up in order to post.