展开运算符只能用于数组,如需合并不同类型,则会出现如下错误提示
Type '(string | number)[]' is not assignable to type 'number[] | string[]'. Type '(string | number)[]' is not assignable to type 'number[]'. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'. <ArkTSCheck>
解决方案
- 定义数组:首先定义了两个数组
arr1
和arr2
,分别包含数字和字符串。 - 创建联合类型数组:定义了一个新的数组
arr3
,它的类型是(number | string)[]
,即数组中的元素可以是数字或字符串。 - 使用展开运算符:通过
...arr1
和...arr2
将两个数组展开,并使用...
展开运算符将它们合并到arr3
中。
let arr3: (number | string) [] = [...arr1, ...arr2]