为什么使用concat减少Array时TypeScript会推断出“从不"类型? [英] Why does TypeScript infer the 'never' type when reducing an Array with concat?

查看:91
本文介绍了为什么使用concat减少Array时TypeScript会推断出“从不"类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码胜于语言,所以:

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

代码非常愚蠢,并返回复制的数组...

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

TS抱怨concat的参数:TS2345:类型'string'的参数不能分配给类型'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[].

这篇关于为什么使用concat减少Array时TypeScript会推断出“从不"类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆