I have this function where I order a group of cards based on a coordinate system:
const orderCardsInPage = (items: OrderItemType[], pageCards: CardType[]) => {
return pageCards.sort((firstCard, secondCard) => {
const orderItemOfFirstCard = items.find((orderItem: OrderItemType) => orderItem.card === firstCard._id.toString());
const orderItemOfSecondCard = items.find((orderItem: OrderItemType) => orderItem.card === secondCard._id.toString());
const valueOfFirstOrderItem = orderItemOfFirstCard?.value;
const valueOfSecondOrderItem = orderItemOfSecondCard?.value;
return valueOfFirstOrderItem! - valueOfSecondOrderItem!;
});
};
However, when I try to compile, my return
statement throws a missing semicolon
error on the non-null assertion symbol (!)
.
I know that the array.find()
function might return an undefined, that's why I have the non-null assertion in place. How can I fix this?
CodePudding user response:
I can't reproduce the error, but what you could do is make sure the values are defined, that way you don't need a non null assertion.
const orderCardsInPage = (items: { value: number }[], pageCards: { _id: number }[]) => {
return pageCards.sort((firstCard, secondCard) => {
const orderItemOfFirstCard = items.find((orderItem: any) => orderItem.card === firstCard._id.toString());
const orderItemOfSecondCard = items.find((orderItem: any) => orderItem.card === secondCard._id.toString());
const valueOfFirstOrderItem = orderItemOfFirstCard?.value;
const valueOfSecondOrderItem = orderItemOfSecondCard?.value;
// for example throw if not found
if (!valueOfFirstOrderItem || !valueOfSecondOrderItem) throw new Error("No item found");
return valueOfFirstOrderItem - valueOfSecondOrderItem;
});
};
Btw I assumed the types, if the value
prop is not optional, you could do the check earlier
const orderCardsInPage = (items: { value: number }[], pageCards: { _id: number }[]) => {
return pageCards.sort((firstCard, secondCard) => {
const orderItemOfFirstCard = items.find((orderItem: any) => orderItem.card === firstCard._id.toString());
const orderItemOfSecondCard = items.find((orderItem: any) => orderItem.card === secondCard._id.toString());
if (!orderItemOfFirstCard || !orderItemOfSecondCard) throw new Error("No item found");
return orderItemOfFirstCard.value - orderItemOfSecondCard.value;
});
};