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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With