As in the example, if I have a type definition for a void function, a function that returns a boolean passes through that type check.
Is this is a bug or is there a valid reason for this? Is there a workaround?
type ReturnsVoid = () => void
type ReturnsNumber = () => number
const a: ReturnsVoid = () => { }
// Surprisingly there is no error
const b: ReturnsVoid = () => { return false; }
// Error - expected
const c: ReturnsNumber = () => { return false; }
// Error - expected
const d: void = false;
Playground
That's intended behavior.
Another way to think of this is that a void-returning callback type says "I'm not going to look at your return value, if one exists".
If it's an acceptible substitution in your case you may have a type returning undefined:
type ReturnsUndefined = () => undefined
type ReturnsNumber = () => number
const a: ReturnsUndefined = () => undefined
const b: ReturnsUndefined = () => { return false; } // error
const c: ReturnsNumber = () => { return false; } // error
playground link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With