Home » Web » TypeScript » TypeScript Boolean Function can Return Undefined

TypeScript Boolean Function can Return Undefined

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;

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;

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;

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;

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;

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.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon.

One Response so far.

  1. Param says:

    Maybe, this style could be shorter if we nee to check for a deeply nested value:

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

Leave a Reply

Your email address will not be published. Required fields are marked *