0

Unable to use the following expression in a react component:

<MyComponent updateCallback={() => void} />

However, this works fine:

<MyComponent updateCallback={() => false} />

Getting error in editor:

Expression expected

In typescript, I am allowed to write following interface:

interface IProps {
  update: () => void;
}`

What is the correct approach for achieving above behaviour without declaring and using it as an interface?

3
  • 1
    () => {} should be equivalent to your "void" function - does something like updateCallback={() => {}} work? Commented Jan 23, 2023 at 13:09
  • @IainShelvington This works if I declare my interface as () => void; But editor gives error if I declare my interface also as () => {}. How come? Commented Jan 23, 2023 at 13:20
  • 1
    Because () => {} as a type annotation means a function that takes no arguments and returns an empty object, not a function that returns nothing Commented Jan 23, 2023 at 13:23

1 Answer 1

2

updateCallback={() => void}

The reason this doesn't work is that that isn't valid javascript. There is a void keyword, but it doesn't get used like this.

The typescript type void is not directly related to the javascript void. When a function has a type update: () => void;, that basically means that whoever calls this function promises not to do anything with the return value. Typically that means you'll return undefined, as in:

updateCallback={() => { return undefined; }}

Or an implicit return:

updateCallback={() => {}}

But if you return something else like false, that's still ok, since the caller will ignore that false.


Going back to the original code you wrote:

updateCallback={() => void}

If you want to have the return type be a typescript void, but you don't want to do an interface for the props, you would do a colon and then a return type, and in the body of the function you do whatever you want.

updateCallback={(): void => {}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.