[SOLVED] Cant push to UnionType array

Issue

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

Solution

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 }[];

//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

Answered By – Derek Lawrence

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *