Search code examples
darttypescastingconditional-operator

Why does using the ternary conditional operator yield a "return_of_invalid_type" error?


func yields an error - A value of type "Object" can't be returned from the function 'func' because it has a return type of 'B'. Why this error specifically? Shouldn't both C() and D() be considered to fit B and therefore have the ternary expression evaluate to an instance of B? If not, why does the ternary expression evaluate to an Object and not an instance of A? This error does not occur using regular conditional syntax (if/else).

class A {}

class B {}

class C extends A implements B {}

class D extends A implements B {}

B func(bool b) => b ? C() : D();

Solution

  • Turns out this is a known issue - see the issues linked here: https://github.com/dart-lang/language/issues/2577