Home > Enterprise >  Why this passed function is giving me an error in typescript?
Why this passed function is giving me an error in typescript?

Time:05-01

In the app.tsx I got a function like this.

Since I am not returning nothing I am setting the return value as void

const addToDo = (newToDoText: string): void => {
    setToDos([...todos, { id: 4, text: newToDoText, completed: false }]);
  };

I passed this function into the form

<ToDoForm addToDo={addToDo} />

The error occur in ToDoForm when I write like this

   //Error Here
    const ToDoForm = ({ addToDo : () => void}) => {

There are two error, 1 on closing bracket } which said expression expected.

Another one is on => arrow which said ; is expected

What am I doing wrong

CodePudding user response:

You seem to be trying to combine property destructuring syntax along with an object type annotation (but they must be exclusive syntax). Try one of these refactors:

TS Playground

// You can type the props separately like this:
type ToDoFormProps = {
  addToDo: (newToDoText: string) => void;
};

// Then you can use them like this:
const ToDoForm1 = (props: ToDoFormProps) => {
  props.addToDo; // (newToDoText: string) => void
};

// You can destructure the "addToDo" property like this:
const ToDoForm2 = ({ addToDo }: ToDoFormProps) => {/* ... */};

// Or you can write the props type inline:
const ToDoForm3 = (props: { addToDo: (newToDoText: string) => void }) => {
  props.addToDo; // (newToDoText: string) => void
};

// Or combine the inline type and destructured property:
const ToDoForm4 = ({ addToDo }: { addToDo: (newToDoText: string) => void }) => {/* ... */};

  • Related