I have been experimenting with UnionTypes in TypeScript and I had an idea for a scenario where they could be useful. However, I am puzzled by the error message that keeps popping up:
Argument of type '{ name: string; }' is not assignable to parameter of type 'string & { name: string; }'
While there are workarounds to make it work, I am more interested in understanding why it is not functioning as expected.
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