google / closure-compiler

A JavaScript checker and optimizer.
https://developers.google.com/closure/compiler/
Apache License 2.0
7.37k stars 1.15k forks source link

Cannot instantiate abstract class #2630

Open shicks opened 7 years ago

shicks commented 7 years ago

Repro

The receiver type for constructor functions is covariant, but when I pass a constructor for an abstract class into a function parameter and then try to instantiate it within the function, the compiler assumes I'm trying to instantiate exactly the abstract base class, rather than admitting the possibility that the instance variable is a concrete subclass.

/** @abstract */ class Foo {}
class Bar extends Foo {}

/** @param {function(new:Foo)} ctor */
function f(ctor) {
  new ctor();
}

f(Bar);

gives the error

WARNING - cannot instantiate abstract class
  new ctor();
  ^^^^^^^^^^

This error is fine when the constructor is known to be for a specific class, but when it's possibly for any subclass, it no longer makes any sense.

facefunk commented 6 years ago

Agreed. Also there seems to be no DiagnosticGroup containing TypeCheck.INSTANTIATE_ABSTRACT_CLASS so the warning can't be suppressed.

mahhov commented 5 years ago

quite ugly, but as a workaround, type casting suppresses the warning.

/** @abstract */ class Foo {}
class Bar extends Foo {}

/**
  * @param {function(new:Foo)} ctor
  * @return {!Foo}
  */
function f(ctor) {
  return /** @type {!Foo} */ (new /** @type {function(new: Object)} */ (ctor)());
}

f(Bar);
EatingW commented 5 years ago

Created Google internal issue b/120664212.