3

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;
2
  • Returning void is not the same as doing nothing. onClick expects a function, and you're giving it one Commented Apr 4, 2022 at 8:16
  • github.com/microsoft/TypeScript/issues/… Commented Apr 4, 2022 at 8:19

1 Answer 1

9

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

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.