可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 a
boolean`
You might need to apply an explicit return type : any
at the function signature. (not sure, I'm not using TS myself)