google / google/closure-compiler
Type checking of `Promise` does not work very well
- Dominant language
- JavaScript
- Stars
- 7.7k
- Forks
- 1.2k
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 6
Description
The type checking of promises has several issues with it.
1. `Promise.resolve` is not type checked correctly when called without argument
```js
/**
* @type {Promise}
*/
const p = Promise.resolve() // should raise error, it resolves to undefined, not string
```
2. Chained promises are not type checked correctly
```js
/**
* @type {Promise}
*/
const p = Promise.resolve().then(function() { return 555 }) // should raise error, it resolves to number, not string
```
3. `new Promise` is not type checked correctly against the type of the variable it is being assigned to
```js
/**
* @type {Promise}
*/
const p = new Promise((resolve, reject) => {
resolve(666) // should raise error, it resolves to number, not string
})
```
4. `new Promise` is not type checked correctly against the type of the variable it is being assigned to even if callbacks are typed explicitly
```js
/**
* @type {Promise} // should raise error, it resolves to string, not number
*/
const p = new Promise(
/**
* @param {function(string): void} resolve
* @param {function(string): void} reject
*/
(resolve, reject) => {
resolve('Hello')
}
)
```
**Extra question**: It is possible that I am just not using the typing syntax correctly. All I want is to assign a new promise to a variable and have strict type checking of both the variable and the promise callbacks. Is there a way to do that?
```js
const p = new Promise((resolve, reject) => { resolve(555) })
```
Related: #2894, #2402
Compiler Version: v20221102
Build command:
```
java -jar ./scripts/closureCompiler.jar \
--entry_point=./src/js/index.js \
--js=./src/**.js \
--dependency_mode=PRUNE \
--warning_level=VERBOSE \
--js_output_file=./dist/bundle.js \
--module_resolution=WEBPACK \
--compilation_level=ADVANCED \
--jscomp_error=checkDebuggerStatement \
--jscomp_error=unusedLocalVariables \
--jscomp_error=reportUnknownTypes \
--jscomp_error=strictCheckTypes;
```
Contributor guide
Assessment
This issue has not been assessed yet.