Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - function that returns boolean passes as a void function

Tags:

typescript

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

like image 690
Maciej Krawczyk Avatar asked Nov 07 '22 01:11

Maciej Krawczyk


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

like image 118
aleksxor Avatar answered Nov 11 '22 05:11

aleksxor