Estoy jugando con UnionTypes en TS y pensé que podría crear un escenario válido donde podrían usarse, pero no entiendo por qué esto está fallando con el error de:
Argumento de tipo '{ nombre: cadena; }' no se puede asignar a un parámetro de tipo 'cadena & { nombre: cadena; }'
Conozco formas de "forzar" este enfoque particular, pero quiero entender por qué esto no funciona.
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 newArrayA menos que desee permitir matrices mixtas ( let newArray: (string | { name: string })[] ), puede usar
// just a boolean to know when is one type or the other if (isMultiple) { const newArray: { name: string }[] = []; otherArray.forEach((item: { name: string }) => { newArray.push(item) }); return newArray; } else { const newArray: string[] = []; otherArray.forEach((item: { name: string }) => { newArray.push(item.name) }); return newArray; }No puede tener ambos tipos de arreglos al mismo tiempo. Puede hacer esto y definirlo y luego crearlo por separado en la declaración if
let newArray: string[] | { name: string }[]; //just a boolean to know when is one type or the other if (isMultiple) { newArray = new Array< { name : string }>(); otherArray.forEach((item: { name: string }) => { newArray.push(item) }) } else { newArray = new Array<string>(); otherArrayforEach((item: { name: string }) => { newArray.push(item.name) }); } return newArray