Output type with connection types - no better general type

So, I am playing with type inference in TypeScript. I will give two examples that cause the same results when called, however in one of them TypeScript cannot infer a type due to "There is no better general type."

Triple operator example

function foo(a: boolean) { return a ? 4 : true; } 

The compiler reports that foo is (a: boolean) => number | boolean (a: boolean) => number | boolean that is awesome.

Example with if statement

 function foo(a: boolean) { if (a) { return 4; } else { return true; } } 

The compiler complains about "There is no better general type" when trying to infer the type of the return value. It bothers me that if statements should bother with the type of inference. Why?

+6
source share
1 answer

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"

+1
source

All Articles