TypeScript Boolean Function can Return Undefined<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

TypeScript Boolean Function can Return Undefined

Posted on: August 3, 2017

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.

1function test1(): boolean{
2 return undefined;

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

1function test2(): boolean{
2 return true && undefined;

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

1function test3(myObject:any): boolean {
2 return myObject && myObject.prop && myObject.prop.isOkay;

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.

1function 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 (!!).

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

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.