Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A compiler error while using ternary operator

Tags:

typescript

I am using typescript 0.9.0.1 in Visual Studio 2012. At a time I use ternary operator in my code, compiler throws an error : Type of conditional expression cannot be determined. Best common type could not be found between void and boolean.

The code is :

export class event
{
    public static add (elem: HTMLElement, ev: string, fn: (ev: Event) => void, thisObj?)
    {
        var callFn = function (ev: Event) { fn.call(thisObj || elem, ev); };

        elem.addEventListener ? elem.addEventListener(ev, callFn, false) : elem.attachEvent('on' + ev, callFn);
    }
}

I try to use if-else instead of ternary operator. Then the error doesn't occur.

The code is :

export class event
{
    public static add (elem: HTMLElement, ev: string, fn: (ev: Event) => void, thisObj?)
    {
        var callFn = function (ev: Event) { fn.call(thisObj || elem, ev); };

        if (elem.addEventListener)
        {
            elem.addEventListener(ev, callFn, false);
        }
        else
        {
            elem.attachEvent('on' + ev, callFn);
        }
    }
}

Is there something wrong with my code?

like image 725
JiaChen ZENG Avatar asked Dec 26 '22 23:12

JiaChen ZENG


1 Answers

The error sais it all. It means one of the cases results to void while the other will result to boolean. As there's no common type for these two types, you can't use them in a ternary operator. Although in your particular case, it could be allowed as you're not assigning the result to a variable.

The error makes more sense if you would assign it to a variable:

var someVar = condition ? aMethodWhichReturnsBoolean : aMethodWhichReturnsVoid;

It should be clear that the compiler cannot know which type someVar would be and furthermore that it can't find another type which would satisfy both boolean and void. Hence it will throw an error.

In your case expanding the ternary operator again to an if/else statement will solve the error, but (to be complete) in the example I have given you'd need to specify the type of someVar as any.

like image 102
thomaux Avatar answered Jan 12 '23 05:01

thomaux