google / google/closure-compiler

Infer return types of callbacks

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

Description

Currently callbacks are inferred after their enclosing scope. This means that if a return type is not declared, we use unknown, which leads to pretty [bad results]:

```js
var /** Promise */ q = Promise.resolve().then(() => 42);
```

This should obviously report an error, and yet it doesn't. Another [example] I saw in the wild:

```js
/** @return {number} */
function cast(/** number|string */ arg) {}

function f(/** number|string */ x) {
x = (function() { return cast(x); })();
var /** null */ z = x;
}
```

[bad results]: https://jscomp-debug.googleplex.com/#input0%3Dvar%2520%252F**%2520Promise%253Cstring%253E%2520*%252F%2520q%2520%253D%2520Promise.resolve().then(()%2520%253D%253E%252042)%253B%26input1%26conformanceConfig%26externs%26refasterjs-template%26includeDefaultExterns%3Dtrue%26CHECK_SYMBOLS%3Dtrue%26MISSING_PROPERTIES%3Dtrue%26TRANSPILE%3Dtrue%26CHECK_TYPES%3Dtrue%26CLOSURE_PASS%3Dtrue%26PRESERVE_TYPE_ANNOTATIONS%3Dtrue%26PRETTY_PRINT%3Dtrue

[example]: https://jscomp-debug.googleplex.com/#input0%3D%252F**%2520%2540return%2520%257Bnumber%257D%2520*%252F%250Afunction%2520cast(%252F**%2520number%257Cstring%2520*%252F%2520arg)%2520%257B%257D%250A%250Afunction%2520f(%252F**%2520number%257Cstring%2520*%252F%2520x)%2520%257B%250A%2520%2520x%2520%253D%2520(function()%2520%257B%2520return%2520cast(x)%253B%2520%257D)()%253B%250A%2520%2520var%2520%252F**%2520null%2520*%252F%2520z%2520%253D%2520x%253B%250A%257D%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

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.