Developer Strange
Developer Strange

Reputation: 2198

got Type 'void' is not assignable to type '() => void' in react typescript

I tried to pass the props like

<Mycomp
 deleteAcc={handleDelete(accountId)}
/>

to another component. I write the props like

interface AccProps {
 deleteAcc: () => void;
}

and call the function like

deleteAcc()

But I got the below error

Type 'void' is not assignable to type '() => void'

Not sure what I have missed here.

Upvotes: 8

Views: 14918

Answers (2)

Ronny Efronny
Ronny Efronny

Reputation: 1498

When you pass handleDelete(accountId) as a prop, the function is called immediately and its return value (in this case, a void) is the one being passed as a prop. If the function must take this particular argument, send it as a callback:

<Mycomp deleteAcc={() => handleDelete(accountId)} />

Since handleDelete(accountId) reutrn void, this callback is typed () => void and therefore suits the prop type.

If the function does not have to accept an argument, you can send it by name:

<Mycomp deleteAcc={handleDelete} />

Often a good idea is to create a unique wrapper function in the component and send it by name, for example:

const wrapper = () => {
  handleDelete(accountId);
};

<Mycomp deleteAcc={wrapper} />

Upvotes: 10

Lin Du
Lin Du

Reputation: 102247

Most likely because the return value type of the handleDelete function is void, and you pass the return value of handleDelete. while deleteAcc requires a function with () => void type.

Try:

<Mycomp deleteAcc={() => handleDelete(accountId)}/>

Upvotes: 4

Related Questions