Md Omar Faruk
Md Omar Faruk

Reputation: 313

How to solve ReactJs (typescript) mapping issue, map() not working

I am trying to update an item from a list of items using map in ReactJs (with TypeScript). But cannot find the issue.

const [orderList, setOrderList] = useState([])

...

setOrderList( orderList.map( order:any => {
    if( order.id == orderId)
        return {...order, review_id:1} 
    return order
}))

the following typescript hint is showing:

Argument of type 'any[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
Type 'any[]' is not assignable to type 'never[]'.
Type 'any' is not assignable to type 'never'.ts(2345)

Thanks in advance

Upvotes: 0

Views: 1401

Answers (3)

Aluan Haddad
Aluan Haddad

Reputation: 31803

First, pass an array of the correct type to useState so that it returns a properly typed state and setter function

const [orderList, setOrderList] = useState([] as Order[]);

This is necessary because the inferred type of the expression [] since there is no context for TypeScript to infer from in this case. In this case I've used a type assertion but there are other ways as well (useState<Order[]>([]) for example).

Second, never put type annotations on inline callback parameters. It's an awful coding pattern that hides bugs and is wholely pointless because type inference ensures safety and correct type propagation.

setOrderList(orderList.map(order => {
  if (order.id === orderId)
    return {...order, review_id: 1};
  return order;
}));

Note:

As noted by others, if you have a unary arrow function that needs a type annotation on its parameter, then you must surround the parameter list with parentheses. For example

const processOrder = (o: Order) => {...};

In the above, we only annotated o with a type because there was no inference context for the language to infer its type.

Upvotes: 2

SFernando
SFernando

Reputation: 1124

just use a parentheses () in the map callback

orderList.map((order:any) => {
  if(order.id === orderId) {
     return {...order, review_id:1} 
  }
  return order
});

Upvotes: 0

francoMG
francoMG

Reputation: 36

Try with const [orderList, setOrderList] = useState<any[]>([]).

By the way, I don't know if you noticed, but the idea of using typescript is to avoid using any.

Upvotes: 1

Related Questions