closure-compiler icon indicating copy to clipboard operation
closure-compiler copied to clipboard

`Array.reduce` method does not get type-checked correctly

Open fingerartur opened this issue 2 years ago • 2 comments

Array.reduce method does not get type-checked correctly.

Eample:

/**
 * @type {Array<number>}
 */
const arr = [1,2,3]
const sum = arr.reduce((a, b) => a + b, 0);

Raises these errors:

./src/js/index.js:12:12: ERROR - [JSC_UNKNOWN_EXPR_TYPE] could not determine the type of this expression
  12| const sum = arr.reduce((a, b) => a + b, 0);
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

./src/js/index.js:12:33: ERROR - [JSC_UNKNOWN_EXPR_TYPE] could not determine the type of this expression
  12| const sum = arr.reduce((a, b) => a + b, 0);
                                       ^

Even though the callback parameters are obviously number and the result as well.

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;

fingerartur avatar Jan 13 '23 09:01 fingerartur

The type-signature of Array.prototype.reduce is defined in the externs, at https://github.com/google/closure-compiler/blob/master/externs/es3.js#L704

It seems like the correct type for reduce would be for the callback first argument and the initial value to both be of type R rather than ?/*.

blickly avatar Jan 13 '23 17:01 blickly

I have just noticed - method Array.reduceRight suffers from the same problem

fingerartur avatar Jan 21 '23 07:01 fingerartur