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?
CodePudding user response:
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 => {}}