Home > Software engineering >  Why return array from array.map is returning with OR operator in typescript?
Why return array from array.map is returning with OR operator in typescript?

Time:03-15

I am new to typescript. I am now trying to map an array and return the result. but the updated result is returning with an or operator

here when I hover the the updated array

let updatedArray: (false | {
 age: number;
 id: number; 
 name: string; 
 username: string;
 email: string;
})[]

From my understanding it should be an array of object only.

Here is the func

 const increseAge = (userId: number): void => {
    //hover over updatedArray here
    let updatedArray = egArray.map((user) => user.id === userId && { ...user, age : user.age   1 });
    
    setEgArray(updatedArray)
  };

CodePudding user response:

The && operator works by evaluating the expression on the left first. If it's falsy, then return that value. If its truthy then evaluate the expression on the right and return it.

user.id === userId && { ...user, age : user.age   1 }

In this case the expression on the left returns a boolean. So either the left express evaluates false and false is returned, or it evaluates true and it returns your user object with the age change.

So false | MyUserType is the type that the function you passed to map actually returns. The result would be an array of all false values expect the one that matched the user id, and that would be the user object with the age change.


You probably want a ternary instead:

egArray.map((user) => (
  user.id === userId
    ? { ...user, age : user.age   1 } // found the user to make older!
    : user // some other user.
   
));

This way every iteration of the loop return a valid user object.

  • Related