Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Typescript type a void function

Why don’t get an error after typing a function that should return nothing and then access props.onClick inside Message component that returns something value?

type MessageProps = {
  onClick: () => void,
  value?: string
}

const Message: React.FunctionComponent<MessageProps> = (props: any) => {
  return (
    <>
      <h1>Example message</h1>
      <button onClick={props.onClick}>click</button>
    </>
  )
}

const App = (props: any) => {
  return (
    <div className="App">
      <Message onClick={() => 2} />
    </div>
  );
}

export default App;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Fundamentally what you’re asking is why this assignment doesn’t result in an error:

type VF = () => void;

const f: VF = () => 2;

(playground)

It’s because a function type with a void return type doesn’t require that the function assigned doesn’t return anything. From the documentation:

Return type void

The void return type for functions can produce some unusual, but expected behavior.

Contextual typing with a return type of void does not force functions to not return something. Another way to say this is a contextual function type with a void return type (type vf = () => void), when implemented, can return any other value, but it will be ignored.

(their emphasis)

If you think about it, that makes sense, since all JavaScript functions return something — if there’s no explicit return, or there’s a return; with no value, the return value is undefined.

function a() { }
function b() { return; }
console.log("a", a());
console.log("b", b());

(I think that’s covered here [for a] and here [for b] in the JavaScript spec, just for what it’s worth.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading