Angular2: No best common type exists among return expressions

匿名 (未验证) 提交于 2019-12-03 08:35:02

问题:

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; } 

回答1:

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; } 


回答2:

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)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!