Angular2:返回表达式中不存在最常见的类型

Sir*_*ini 13 typescript angular

尝试用gulp编译我的打字稿但是我会收到以下错误:

No best common type exists among return expressions.

代码是一个如下所示的for循环:

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

    return false;
}
Run Code Online (Sandbox Code Playgroud)

Lor*_*ual 15

正如@günter-zöchbauer所提到的,你的函数确实返回了两种不同的类型.如果你真的想在一个案例中返回一个数字,否则你可以使用布尔any值作为函数的返回值来解决这个问题.

然而,正如许多其他功能,如indexOf返回数字,即使没有找到值,我建议你也这样做.在您的情况下,-1如果找不到该项,您也可以返回.通过这种方式,您可以明确您的类型,并为其他人提供清晰的界面.

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;
}
Run Code Online (Sandbox Code Playgroud)