Skip to content

Instantly share code, notes, and snippets.

@thomasboyt
Created April 8, 2016 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasboyt/948dd82ca870307839531952c54c6436 to your computer and use it in GitHub Desktop.
Save thomasboyt/948dd82ca870307839531952c54c6436 to your computer and use it in GitHub Desktop.
const arr = <any>[1,2,3];
// why does typescript think sum is `any` instead of `num`? shouldn't it use the type of
// initialValue here?
const arrSum = arr.reduce((acc, val) => acc + val, 0); // arrSum is `any`
// ImmutableJS does this correctly:
import I from 'immutable';
const list = I.List<any>().push(1).push(2).push(3);
const listSum = list.reduce((acc, val) => acc + val, 0); // listSum is `number`
@thomasboyt
Copy link
Author

typescript's definition looks like it should work fine:

reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T;
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;

but doesn't?

for comparison, flow:

reduce<U>(
  callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: Array<T>) => U,
  initialValue: U
): U;
reduce<U>(
  callbackfn: (previousValue: T|U, currentValue: T, currentIndex: number, array: Array<T>) => U
): U;

and immutable:

reduce<R>(
  reducer: (reduction?: R, value?: V, key?: K, iter?: /*this*/Iterable<K, V>) => R,
  initialReduction?: R,
  context?: any
): R;

@thomasboyt
Copy link
Author

looks like this is the culprit: microsoft/TypeScript#7014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment