This error will be raised if the return statements in the function do not have a common type. This can only happen if there are multiple return statements.
The first example is a single return statement
In the first example, there is only one return statement that returns the value entered as number | boolean number | boolean (brackets added to emphasize this one expression):
return (a ? 4 : true); // return number | boolean
It's good. There are no other return statements that must be associated with a type.
Second example - multiple return statements
The second example contains several return statements ...
if (a) { return 4; // return number } else { return true; // return boolean }
... and among the many operators there is no general type. So these are mistakes.
Multiple Return Statement Solution
If there is no common type between the return statements, you need to be explicit so that the compiler knows that you want to do this:
function foo(a: boolean): number | boolean { if (a) { return 4; } else { return true; } }
Related: See "Best General Type"
source share