为什么在使用 concat 减少数组时,TypeScript 会推断出“从不"类型?

人气:431 发布:2022-10-16 标签: functional-programming typescript reduce reducers strictnullchecks

问题描述

代码胜于语言,所以:

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

代码很傻,返回一个复制的数组...

The code is very silly and returns a copied Array...

TS 抱怨 concat 的参数:TS2345:字符串"类型的参数不能分配给ConcatArray"类型的参数.

TS complains on concat's argument: TS2345: Argument of type 'string' is not assignable to parameter of type 'ConcatArray'.

推荐答案

我相信这是因为 [] 的类型被推断为 never[],即是必须为空的数组的类型.您可以使用类型转换来解决这个问题:

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[]);

通常这不会是什么大问题,因为 TypeScript 在找出更好的类型以根据您对空数组的处理方式分配给空数组方面做得不错.但是,由于您的示例正如您所说的那样愚蠢",因此 TypeScript 无法进行任何推断并将类型保留为 never[].

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

320