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

时间:2016-03-26 03:34:12

标签: meteor typescript angular meteor-collection2 angular2-meteor

当我在angular2-meteor项目中使用Collection2时,来自demo的这些代码总是在终端中给我警告:

  

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

如何改进代码?感谢

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

1 个答案:

答案 0 :(得分:9)

由于每个返回分支都需要一种Date类型,因此必须为每个if / else分支返回Date类型,或者可以创建一个返回两种不同类型的union。

在任何一种情况下,如果类型为Date,则可以为第三个条件返回null。这在打字稿中有效。

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