javascript - Typescript将两种数据类型数组合二为一
问题描述
如何使用concat
. 如果我用两种数据类型对其进行初始化,它可以正常工作,但是当我concat
这样做时。Typescript 抛出两种类型不兼容的错误。
const foo: string[] = ['hello', 'world'];
const bar: number[] = [1, 2];
const both: (string | number)[] = foo.concat(bar); // gets an error on bar
const other: (string | number)[] = ['hello', 'world', 2, 3]; // this works
解决方案
我认为这与.concat()
Typescript 中的实现有关。它被实现为合并数组的类型预计是foo
这里的类型。这就是它抛出错误的原因。
您可以在此处从 Typescript Playground检查代码片段的错误选项卡,以了解更多信息。
如果你想让它工作,你可以使用扩展运算符。它应该可以正常工作。
const foo: string[] = ['hello', 'world'];
const bar: number[] = [1, 2];
const both: (string | number)[] = [...foo, ...bar];
推荐阅读
- node.js - 如何使用 Azure api 启动容器实例?
- php - 无法使用 Outlook SMTP 帐户发送电子邮件
- html - 你好未定义
- java - java中的冒泡排序,方法(静态或非静态)?,(void or int[])?,需要实例变量吗?
- javascript - 删除任务函数 JQuery 删除键
- python - dev_appserver.py app.yaml 产生:ImportError: Importing the multiarray numpy extension module failed
- python - 为什么 add_child 方法在我使用 folium 库的地理映射代码中不起作用?
- html - 移动 Safari 菜单链接和页脚不显示字体系列
- c++ - 鼠标单击时的 C++ 屏幕截图不起作用
- xml - XSLT 2.0 围绕指定的子元素拆分元素