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

26,358

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:

  1. Use string[] as the generic type parameter of the reduce method (thanks @depoulo for mentioning it):
['a', 'b', 'c'].reduce<string[]>((accumulator, value) => accumulator.concat(value), []);
  1. 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 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.

  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)
    

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.

Share:
26,358

Related videos on Youtube

millsp
Author by

millsp

Building developer-friendly packages 🍕 with TypeScript &amp; React 🚀

Updated on February 12, 2022

Comments

  • millsp
    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
    Patrick Roberts over 5 years
    "Why does TypeScript infer the 'never' type?" "because the type for [] is inferred to be never[]". If that was the case then why does const array = []; infer array as type any[]?
  • Matt H
    Matt H over 5 years
    Normally 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 an any[] 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 the never[] type instead of the any[] type.
  • jcalz
    jcalz over 5 years
    Relevant: github.com/Microsoft/TypeScript/issues/18687 It's more complicated than I realized, but [] gets inferred as some kind of "widening any[]" type when contextually typed... apparently in a way that doesn't happen when being passed as the accumulator in reduce(). 🤷‍♀️
  • millsp
    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
    depoulo about 3 years
    This should be the accepted answer. Slightly different solution, using generics: ['a', 'b', 'c'].reduce<string[]>((accumulator, value) => accumulator.concat(value), []);
  • Ammamon
    Ammamon over 2 years
    Thank you Andru for your valuable feedback. I too had the same issue; so googled and arrived at your correct answer.
  • jcalz
    jcalz over 2 years
    Just found github.com/microsoft/TypeScript/issues/29795 which could be an authoritative source of the above info
  • Andrew Halil
    Andrew Halil over 2 years
    This 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