无法推送到 UnionType 数组
我正在 TS 中使用 UnionTypes,我认为我可以创建一个可以使用它们的有效场景,但我不明白为什么会出现以下错误:
类型参数 '{ name: string; }' 不可分配给类型为 'string & 的参数{ 名称:字符串; }'
知道“强制”这种特定方法的方法,但我想了解为什么这不起作用。
let newArray: string[] | { name: string }[] = new Array();
//just a boolean to know when is one type or the other
if (isMultiple) {
otherArray.forEach((item: { name: string }) => {
newArray.push(item)
})
}
else {
otherArray.forEach((item: { name: string }) => {
newArray.push(item.name)
});
}
return newArray
I am playing around with UnionTypes in TS and I thought that I could create a valid scenario where they could be used, but I do not understand why this is breaking with the error of:
Argument of type '{ name: string; }' is not assignable to parameter of type 'string & { name: string; }'
I know ways to "force" this partical approach, but I want to understand why this does not work.
let newArray: string[] | { name: string }[] = new Array();
//just a boolean to know when is one type or the other
if (isMultiple) {
otherArray.forEach((item: { name: string }) => {
newArray.push(item)
})
}
else {
otherArray.forEach((item: { name: string }) => {
newArray.push(item.name)
});
}
return newArray
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能同时拥有两种类型的数组。您可以执行此操作并定义它,然后在 if 语句中单独创建它
You cant have both types of arrays at the same time. You could do this and define it then create it separately in the if statement
除非你想允许混合数组(
let newArray: (string | { name: string })[]
),你可以使用Unless you want to allow mixed arrays (
let newArray: (string | { name: string })[]
), you can use