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

Hon*_*iao 8 meteor typescript meteor-collection2 angular2-meteor angular

当我在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();
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*d L 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;
    }
}
Run Code Online (Sandbox Code Playgroud)