Home > Software design >  Typescript union type issue (doesn't react to union)
Typescript union type issue (doesn't react to union)

Time:11-26

I have a really weird issue:

TS2322: Type '(arg0: Person[]) => void' is not assignable to type '(arg0: Person | Person[]) => void'.

Wtf is going on here? Function parameter union type tells that it can be a array or not, but doesn't work. Looks like typescript bug?

This code calls it, error is shown on onAdd:

onAdd={(item: Person[]) => {
  const persons = item.map((el) => el.name);
}}

And the type of onAdd is this:

onAdd?: (person: Person| Person[]) => void;

CodePudding user response:

Typescript is pointing out a real issue in your code.

onAdd?: (entity: Person| Person[]) => void;

This type means that when you call onAdd, you might be passing in a Person, or you might be passing in a Person[]. No way to know in advance. As a result, any function that's passed as the onAdd prop needs to be able to handle both cases.

onAdd={(item: Person[]) => {
  const persons = item.map((el) => el.name);
}}

This function will break if called with an individual person. If item is an individual person, then it won't have a .map method, and you'll get a runtime exception. So, typescript detects that the functions are incompatible, and gives you the error.

The likely fix is to change your function so it can work with individual person objects:

onAdd={(item: Person | Person[]) => {
  const persons = Array.isArray(item) ? item.map(el => el.name) : [item.name];
}}

Another possibility is that (entity: Person | Person[]) => void; is not the type you meant, but in that case i'll need more information about what your goal is in order to suggest a solution.

CodePudding user response:

Just fix ur onAdd function to this:

onAdd={(item: Person | Person[]) => { const persons = Array.isArray(item) ? item.map(element => element.name) : [item.name]; }}

  • Related