Home > Software design >  React Typescript type a void function
React Typescript type a void function

Time:04-04

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;

CodePudding user response:

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.)

  • Related