Skip to content

Reduce without an initialValue should be illegal on a potentially empty array #34736

Closed as not planned
@calimeroteknik

Description

@calimeroteknik

TypeScript Version: 3.8.0-dev.20191025

Search Terms: reduce no initialvalue

Code

[].reduce((a,b) => a+b /*, initialvalue NOT specified*/);

Expected behavior:
Should not compile

Actual behavior:
Compiles and crashes:

~ $ tsc reduce.ts; echo $?
0
~ $ js reduce.js
reduce.js:1: TypeError: reduce of empty array with no initial value

Related Issues:
None relevant, #28901 is trying to make TS accept something that it doesn't accept currently; I'm asking the opposite: that something which is accepted became not accepted.

Some ideas:
Retiring reduce with no initialValue from the type Array as this is unsafe to keep around; people should provide an initialValue if their array can be empty:

--- a/typescript/lib/lib.es5.d.ts	2019-10-25 12:33:06.312693040 +0200
+++ b/typescript/lib/lib.es5.d.ts	2019-10-25 12:34:11.071987865 +0200
@@ -1329,6 +1329,7 @@
       * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
       * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
       */
-    reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
     reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
     /**
       * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

In order to use reduce without initialValue on arrays for which it will work, it's possible to introduce something that might or might not be along the lines of:

type NonEmptyArray<T> = [T, ...T[]];

This non-empty array type can safely reintroduce the reduce signature without initialValue, the very one I would like to retire from the (possibly empty) Array type.

People who want to live dangerously could still use ([] as NonEmptyArray).reduce(someOperation) if they absolutely refuse to provide an initialValue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    SuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions