Why does TypeScript infer the 'never' type

2020-08-09 08:21发布

问题:

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'.

回答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[].



回答2:

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)