简体   繁体   中英

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

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.

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 .

just use a parentheses () in the map callback

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM