Why does TypeScript infer the 'never' type when reducing an Array with concat? Why does TypeScript infer the 'never' type when reducing an Array with concat? typescript typescript

Why does TypeScript infer the 'never' type when reducing an Array with concat?


I believe this is because the type for [] is inferred to be never[], which is the type for an array that MUST be empty. You can use a type cast to address this:

['a', 'b', 'c'].reduce((accumulator, value) => accumulator.concat(value), [] as string[]);

Normally this wouldn't be much of a problem since TypeScript does a decent job at figuring out a better type to assign to an empty array based on what you do with it. However, since your example is 'silly' as you put it, TypeScript isn't able to make any inferences and leaves the type as never[].


Better solution which avoids a type cast:

Type the accumulator value as string[] (and avoid a type cast on []):

['a', 'b', 'c'].reduce((accumulator: string[], value) => accumulator.concat(value), []);

Play with this solution in the typescript playground.

Notes:

  1. Type casts should be avoided if you can because you're taking one type and transpose it onto something else. This can cause side-effects since you're manually taking control of coercing a variable into another type.

  2. This typescript error only occurs if the strictNullChecks option is set to true. The Typescript error disappears when disabling that option, but that is probably not what you want.

  3. I reference the entire error message I get with Typescript 3.9.2 here so that Google finds this thread for people who are searching for answers (because Typescript error messages sometimes change from version to version):

    No overload matches this call.  Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error. Argument of type 'string' is not assignable to parameter of type 'ConcatArray<never>'.  Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error. Argument of type 'string' is not assignable to parameter of type 'ConcatArray<never>'.(2769)


You should use generics to address this.

['a', 'b', 'c'].reduce<string[]>((accumulator, value) => accumulator.concat(value), []);

This will set the type of the initial empty array, which in my opinion is the most correct solution.