Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: No best common type exists among return expressions

Trying to compile my typescript with gulp but I'll get the following error:

No best common type exists among return expressions.

Where the code is a for loop which looks like this:

   getIndexInCompareList(result) {
    for (var i = 0; i < this.compare.length; i++) {
        if (this.compare[i].resource.id == result.resource.id) {
            return i;
        }
    }

    return false;
}
like image 905
Sireini Avatar asked May 25 '16 14:05

Sireini


2 Answers

As @günter-zöchbauer mentioned, your function does return two different types. If you really want to return a number in one case and otherwise a boolean you could use any as your return value for the function to fix this issue.

However, as many other functions such as indexOf return numbers only even if the value was not found I would suggest you do the same. In your case you could also return -1 if the item was not found. This way you can be explicit about your types and also provide a clear interface for others.

function getIndexInCompareList(result): number {
    for (let i = 0; i < this.compare.length; i++) {
        if (this.compare[i].resource.id == result.resource.id) {
            return i;
        }
    }

    return -1;
}
like image 64
LordTribual Avatar answered Nov 12 '22 09:11

LordTribual


return i; returns a number, return false returns aboolean`

You might need to apply an explicit return type : any at the function signature. (not sure, I'm not using TS myself)

like image 4
Günter Zöchbauer Avatar answered Nov 12 '22 10:11

Günter Zöchbauer