Code speaks better than language, so:
['a', 'b', 'c'].reduce((accumulator, value) => accumulator.concat(value), []);
The code is very silly and returns a copied Array...
TS complains on concat's argument: TS2345: Argument of type 'string' is not assignable to parameter of type 'ConcatArray'.
I believe this is because the type for
[]
is inferred to benever[]
, which is the type for an array that MUST be empty. You can use a type cast to address this: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 asstring[]
(and avoid a type cast on[]
):Play with this solution in the typescript playground.
Notes:
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.
This typescript error only occurs if the
strictNullChecks
option is set totrue
. The Typescript error disappears when disabling that option, but that is probably not what you want.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):