Patrick Desjardins Blog
Patrick Desjardins picture from a conference

TypeScript Boolean Function can Return Undefined

Posted on: 2017-08-03

As much as I like TypeScript, it sometime inherits of the bad side of JavaScript. In this article, I'll demonstrate a common example that cause problem. It goes in the line of what I wrote a year ago about the difference between NULL or undefined. While it's always better to check for === undefined, lot of people keep having the habit of just checking the value with &&.

Before getting into the core of the issue. Let's be on the same page. The following code compiles.

function test1(): boolean{ 
  return undefined; 
} 
alert(test1()); 

It doesn't look like it compiles, but it does. Which mean that the following code also compile and return undefined as well.

function test2(): boolean{ 
  return true && undefined; 
}
alert(test2()); 

But you will say that you will never explicitly write undefined in an && condition. However, people write:

function test3(myObject:any): boolean { 
  return myObject && myObject.prop && myObject.prop.isOkay; 
} 
alert(test3()); 

The alert in that case will be undefined if the "prop" is not defined or if the myObject is not defined. It won't be false.

There is two ways to solve that issue. The first one is the proper way, but longer way to write which is to check against what we are really evaluating -- undefined.

function test4(myObject:any): boolean { return myObject !== undefined && myObject.prop !== undefined && myObject.prop.isOkay; } alert(test4()); 

This is the most explicit and clear way to have exactly the result expected. It returns true or it returns false; it cannot return undefined.

A more succinct way to write this validation is to use the double bang (!!).

function test5(myObject:any): boolean {
   return !!myObject && !!myObject.prop && myObject.prop.isOkay; 
} 
alert(test5()); 

This latest will also evaluate for null as well as undefined and also true/false.

At the end, you should always avoid to simply rely that an undefined value will return false in a chain of condition. JavaScript return the last value that is not true in the chain, which we saw that can be undefined. TypeScript is not smart enough to catch this possibility and will let the function returning undefined instead of a boolean.