google / google/closure-compiler
Should warn when a method is passed as a function
- Dominant language
- JavaScript
- Stars
- 7.7k
- Forks
- 1.2k
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 6
Description
[This code][1] should warn but does not:
```js
/** @constructor */
function Foo() {}
/** @param {number} arg */
Foo.prototype.bar = function(arg) {};
/** @param {function(number)} f */
function map(f) {}
map(new Foo().bar);
```
This is tricky because the `this:` parameter to a function needs some special handling: it's covariant when it's a constructor (in that case, it's actually `new:`, but it's stored in the same field, internally), but contravariant for methods, except when overriding, where `function(this:SubFoo, SuperBar): SubBaz` can indeed override `function(this:SuperFoo, SubBar): SuperBaz`.
Moreover, it looks like not specifying it essentially makes us treat it as unknown: an explicit `this: undefined` in the callback signature *does* [recover the error][2], and still works correctly for non-methods. So this is very similar to the issue of treating `function()` as returning unknown rather than undefined.
This issue seems related to #2895 and we may want to address them together.
[1]: https://closure-compiler-debugger.appspot.com/#input0%3D%252F**%2520%2540constructor%2520*%252F%250Afunction%2520Foo()%2520%257B%257D%250A%250A%252F**%2520%2540param%2520%257Bnumber%257D%2520arg%2520*%252F%250AFoo.prototype.bar%2520%253D%2520function(arg)%2520%257B%257D%253B%250A%250A%252F**%2520%2540param%2520%257Bfunction(number)%257D%2520f%2520*%252F%250Afunction%2520map(f)%2520%257B%257D%250A%250Amap(new%2520Foo().bar)%253B%26input1%26conformanceConfig%26externs%26refasterjs-template%26CHECK_SYMBOLS%3Dtrue%26MISSING_PROPERTIES%3Dtrue%26TRANSPILE%3Dtrue%26CHECK_TYPES%3Dtrue%26CLOSURE_PASS%3Dtrue%26PRESERVE_TYPE_ANNOTATIONS%3Dtrue%26PRETTY_PRINT%3Dtrue
[2]: https://closure-compiler-debugger.appspot.com/#input0%3D%252F**%2520%2540constructor%2520*%252F%250Afunction%2520Foo()%2520%257B%257D%250A%250A%252F**%2520%2540param%2520%257Bnumber%257D%2520arg%2520*%252F%250AFoo.prototype.bar%2520%253D%2520function(arg)%2520%257B%257D%253B%250A%250A%252F**%2520%2540param%2520%257Bnumber%257D%2520arg%2520*%252F%250Afunction%2520baz(arg)%2520%257B%257D%250A%250A%252F**%2520%2540param%2520%257Bfunction(this%253A%2520undefined%252C%2520number)%257D%2520f%2520*%252F%250Afunction%2520map(f)%2520%257B%257D%250A%250Amap(new%2520Foo().bar)%253B%250Amap(baz)%253B%26input1%26conformanceConfig%26externs%26refasterjs-template%26CHECK_SYMBOLS%3Dtrue%26MISSING_PROPERTIES%3Dtrue%26TRANSPILE%3Dtrue%26CHECK_TYPES%3Dtrue%26CLOSURE_PASS%3Dtrue%26PRESERVE_TYPE_ANNOTATIONS%3Dtrue%26PRETTY_PRINT%3Dtrue
Contributor guide
Assessment
This issue has not been assessed yet.