Home > Mobile >  Cant push to UnionType array
Cant push to UnionType array

Time:03-25

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

CodePudding user response:

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

CodePudding user response:

Unless you want to allow mixed arrays (let newArray: (string | { name: string })[]), you can use

// 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;
}
  • Related