No best common type exists among return expressions
Asked Answered
C

1

8

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();
      }
    }
  }
}
Caraway answered 26/3, 2016 at 3:34 Comment(4)
It's telling you precisely what the error is. You're returning a Date, an object, and whatever is returned by this.unset() (probably nothing, that seems like a void). So you have absolutely ZERO common return types. Pick a type and return that type consistently.Lollis
@DavidL thanks, I tried to add a return undefined; after this.unset();, but it still gives me the warning.Caraway
autoValue function doesn't have appropriate return type and also this.unsert is not clear. set some return type to that function.Govern
The codes are from demo. I don't know how to return same type correctly.Caraway
L
9

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;
    }
}
Lollis answered 26/3, 2016 at 3:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.