Angular2:返回表达式之间不存在最佳通用类型 [英] Angular2: No best common type exists among return expressions
问题描述
尝试用gulp编译我的打字稿,但会出现以下错误:
Trying to compile my typescript with gulp but I'll get the following error:
返回表达式之间不存在最佳的通用类型.
其中的代码是一个 for
循环,如下所示:
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;
}
推荐答案
正如@günter-zöchbauer所述,您的函数确实返回两种不同的类型.如果您真的想在一种情况下返回数字,否则返回布尔值,则可以使用 any
作为该函数的返回值来解决此问题.
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.
但是,即使没有找到该值,许多其他函数(例如 indexOf
)也会返回数字,我建议您也这样做.对于您而言,如果未找到该项目,您还可以返回 -1
.通过这种方式,您可以明确显示自己的类型,还可以为其他人提供清晰的界面.
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;
}
这篇关于Angular2:返回表达式之间不存在最佳通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!