google / google/closure-compiler

Cannot instantiate abstract class

Open
#2,630 3 comments 4 reactions 0 assignees View on GitHub
triage-done
Dominant language
JavaScript
Stars
7.7k
Forks
1.2k
Avg merge
2d 12h
Merged PRs (30d)
6

Description

[Repro][1]

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.

```js
/** @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.

[1]: https://closure-compiler-debugger.appspot.com/#input0%3D%252F**%2520%2540abstract%2520*%252F%2520class%2520Foo%2520%257B%257D%250Aclass%2520Bar%2520extends%2520Foo%2520%257B%257D%250A%250A%252F**%2520%2540param%2520%257Bfunction(new%253AFoo)%257D%2520ctor%2520*%252F%250Afunction%2520f(ctor)%2520%257B%250A%2520%2520new%2520ctor()%253B%250A%257D%250A%250Af(Bar)%253B%26input1%26conformanceConfig%26externs%3Dfunction%2520Symbol()%2520%257B%257D%250A%252F**%2520%2540constructor%2520%2540return%2520%257B!Object%257D%2520*%252F%2520function%2520Object(%252F**%2520*%253D%2520*%252F%2520opt_arg)%2520%257B%257D%250AObject.create%2520%253D%2520function(%252F**%2520...%253F%2520*%252F%2520var_args)%2520%257B%257D%253B%250AObject.getOwnPropertyDescriptor%2520%253D%2520function(%252F**%2520...%253F%2520*%252F%2520var_args)%2520%257B%257D%253B%250AObject.defineProperty%2520%253D%2520function(%252F**%2520...%253F%2520*%252F%2520var_args)%2520%257B%257D%253B%250AObject.setPrototypeOf%2520%253D%2520function(%252F**%2520...%253F%2520*%252F%2520var_args)%2520%257B%257D%253B%250AObject.prototype.constructor%253B%250A%252F**%2520%2540constructor%2520*%252F%2520function%2520Function(%252F**%2520...*%2520*%252F%2520var_args)%2520%257B%257D%250AFunction.prototype.apply%2520%253D%2520function(%252F**%2520...%253F%2520*%252F%2520var_args)%2520%257B%257D%253B%250A%252F**%2520%2540constructor%2520%2540return%2520%257B!TypeError%257D%2520*%252F%2520function%2520TypeError(%252F**%2520*%253D%2520*%252F%2520opt_arg0%252C%252F**%2520*%253D%2520*%252F%2520opt_arg1%252C%252F**%2520*%253D%2520*%252F%2520opt_arg2)%2520%257B%257D%250A%26refasterjs-template%26CHECK_SYMBOLS%3D1%26MISSING_PROPERTIES%3D1%26TRANSPILE%3D1%26CHECK_TYPES%3D1%26CLOSURE_PASS%3D1%26PRESERVE_TYPE_ANNOTATIONS%3D1%26PRETTY_PRINT%3D1

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.