No best common type exists among return expressions

旧时模样 提交于 2019-12-09 17:21:34

问题


When I use Collection2 in angular2-meteor project, these kinds of codes from demo always give me warning in the terminal:

No best common type exists among return expressions.

How can I improve the codes? Thanks

{
  createdAt: {
    type: Date,
    autoValue: function() {
      if (this.isInsert) {
        return new Date();
      } else if (this.isUpsert) {
        return {$setOnInsert: new Date()};
      } else {
        this.unset();
      }
    }
  }
}

回答1:


Since a type of Date is expected for EVERY return branch, you must return a Date type for every if/else branch OR you can create a union that returns two different types.

In either case, you can return null for the third condition if the type is Date. That is valid in typescript.

autoValue: function() : Date|Object  {
    if (this.isInsert) {
        return new Date();
    } else if (this.isUpsert) {
        return {$setOnInsert: new Date()};
    } else {
        this.unset();
        return null;
    }
}


来源:https://stackoverflow.com/questions/36231334/no-best-common-type-exists-among-return-expressions

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