TypeScript - function that returns boolean passes as a void function

Viewed 645

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

1 Answers

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

Related