Why does TypeScript infer the 'never' type when reducing an Array with concat?
Solution 1
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[]
.
Solution 2
A better solution which avoids a type assertion (aka type cast) in two variants:
- Use
string[]
as the generic type parameter of thereduce
method (thanks @depoulo for mentioning it):
['a', 'b', 'c'].reduce<string[]>((accumulator, value) => accumulator.concat(value), []);
- Type the
accumulator
value asstring[]
(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:
-
Type assertions (sometimes called 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):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)
Solution 3
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.
Related videos on Youtube
millsp
Building developer-friendly packages 🍕 with TypeScript & React 🚀
Updated on February 12, 2022Comments
-
millsp about 2 years
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'.
-
Patrick Roberts over 5 years"Why does TypeScript infer the 'never' type?" "because the type for
[]
is inferred to benever[]
". If that was the case then why doesconst array = [];
inferarray
as typeany[]
? -
Matt H over 5 yearsNormally TypeScript does a pretty good job at inferring the proper type for an empty array based on how it is used. However, it isn't able to in this example because it doesn't have any types in the parameters or return type of the callback, and it doesn't use the original ['a', 'b', 'c'] array for type inferencing. Doing something like
const array = [];
does indeed produce anany[]
array. However, I think this is an explicit exception to avoid confusing people. If you do something like[].filter(a => true);
, you will see that it infers thenever[]
type instead of theany[]
type. -
jcalz over 5 yearsRelevant: github.com/Microsoft/TypeScript/issues/18687 It's more complicated than I realized, but
[]
gets inferred as some kind of "wideningany[]
" type when contextually typed... apparently in a way that doesn't happen when being passed as the accumulator inreduce()
. 🤷♀️ -
millsp over 5 years@MattH Yes TS isn't able to determine the type of the array, you can either cast or pass the type as a template parameter to reduce then it works !
-
depoulo about 3 yearsThis should be the accepted answer. Slightly different solution, using generics:
['a', 'b', 'c'].reduce<string[]>((accumulator, value) => accumulator.concat(value), []);
-
Ammamon over 2 yearsThank you Andru for your valuable feedback. I too had the same issue; so googled and arrived at your correct answer.
-
jcalz over 2 yearsJust found github.com/microsoft/TypeScript/issues/29795 which could be an authoritative source of the above info
-
Andrew Halil over 2 yearsThis does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review