The absence of a semicolon in the non-null assertion is causing an

Within my code, I have a function that arranges a set of cards according to a specific 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!;
    });
};

When attempting to compile the code, an error is thrown at the return statement due to a missing semicolon error on the non-null assertion symbol (!).

Recognizing that the array.find() function may result in undefined values, I utilized the non-null assertion. How can this issue be resolved?

Answer №1

The error cannot be duplicated, but it is recommended to ensure that the values are defined to avoid the need for 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;
    // throw an error if either value is not found
    if (!valueOfFirstOrderItem || !valueOfSecondOrderItem) throw new Error("No item found");
    return valueOfFirstOrderItem - valueOfSecondOrderItem;
  });
};

By the way, I made assumptions about the types. If the value property is not optional, consider performing the check earlier in the code.

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;
  });
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the proper way to showcase the hover effect on a nested ul list item in the DOM?

In an attempt to create a menu, I have written the following code: var sheet_nav = document.createElement('style'); sheet_nav.innerHTML = "nav{ margin: 100px auto; text-align: center;}"; document.head.appendChild(sheet_nav); var sheet_nav_ul = ...

"Transitioning from jQuery to Vanilla Javascript: Mastering Scroll Animations

I'm seeking guidance on how to convert this jQuery code into pure Javascript. $('.revealedBox').each(function() { if ($(window).scrollTop() + $(window).height() > $(this).offset().top + $(this).outerHeight()) { $(this).addCla ...

Ways to retrieve information from a POST request

I am looking for assistance on extracting data from a post request and transferring it to Google Sheets while also confirming with the client. Any guidance or support would be highly appreciated. Thank you. My project involves creating a web application f ...

What is the best way to display the weather information for specific coordinates in ReactJS?

I've been working on a code that retrieves farm details based on longitude and latitude. My goal now is to fetch the weather information for that specific farm using openweathermap However, each time I attempt to do so, an error message {cod: '4 ...

Learn how to hide elements on print pages conditionally in Vue.js using CSS or JavaScript

I am currently using the Vue framework to work on printing webpages for my application. I have an issue that needs a solution, which I will explain below. <template> <div id = "intro" style = "text-align:center;"> <div ...

How can the data controller of a model be accessed within a directive that has been defined with "this"?

I'm struggling with accessing data using a directive, especially when I have defined my models like this: vm = this; vm.myModel = "hello"; Here is an example of my directive: function mySelectedAccount(){ return { restrict: 'A&ap ...

Refreshing the form fields and storing the information using AngularJS

I have successfully implemented a basic form using AngularJS. The issue I am facing is that even after the user enters their details and submits the form, the values remain in the input fields. My goal is to store the details of multiple fields in the con ...

Can the CSS of an iframe be modified if the iframe is located on a different domain?

Is it feasible to modify the CSS of an iframe if the iframe is not located on the same domain? If so, what are some ways to apply and alter CSS for this situation? Any assistance would be greatly appreciated. <iframe id="frame1" width="100%" height="35 ...

Is there a way to replicate table cells in the style of Excel using jQuery?

Excel has a convenient feature that allows cells to be copied by dragging and dropping with the mouse. This same functionality is also available in Google Spreadsheets. I am trying to understand how Google has implemented this feature using JavaScript cod ...

React: Issue accessing URL parameters using useParams() within a nested component

In my demo application, there are two components - QuoteDetail and Comments. Both require URL parameters, but I am only able to access them in the parent component. App.tsx: <Switch> // ... <Route path="/quotes" exact> <Al ...

Ways to implement a conditional statement to display a div using JavaScript

Looking for a way to utilize Javascript conditions to toggle the visibility of a div in an HTML5 document? Check out this code snippet below: #demo { width: 500px; height: 500px; background-color: lightblue; display: none; } To set the f ...

Utilizing React to create an infinite loop, where an onClick event triggers an image change that updates the source of

I'm experiencing an infinite loop in my React application. I'm attempting to include a previous Image and next Image button in the development stage using an image tag. However, when my component loads up, I encounter errors. Does anyone have a ...

javascript identify dissimilarities within arrays

Working on an Angular 2 application and attempting to identify the difference between two arrays (last seven days and missing dates within the last seven days). Everything works fine when initializing the array through a string, like in example code 1. How ...

"Exploring locations with Google Maps and integrating them into interactive

I recently encountered an issue while working on a node express application and integrating the google maps javascript api. The problem arose when I attempted to transfer the sample code from the google website, along with my API key, into a .ejs file. S ...

Accessing information from RESTful Web Service with Angular 2's Http functionality

I am currently working on retrieving data from a RESTful web service using Angular 2 Http. Initially, I inject the service into the constructor of the client component class: constructor (private _myService: MyService, private route: Activat ...

Display the closest locations on the Google Maps interface

I am currently working on a project that involves integrating Google Maps. The project includes storing hospital addresses (in longitude and latitude) in a database. However, I need assistance in displaying the nearest hospital from my current location. I ...

Executing <script> tags inside <template> on vue js

I have encountered a problem while trying to add an Iframe from a service I am using. The content comes within script tags, but when I try to insert them into Vue 3 framework, I encounter an error. I have searched for a solution and came across a thread o ...

Implementing Angular to activate the JavaScript 'click' event

I am attempting to initiate an 'onclick' event within an angular controller. <div id="galerie"> <h2>{{main.Page.title()}}</h2> <hr> <div class="row"> <div class="col-sm-4 col-xs-6" ng-repeat= ...

How to apply props conditionally in VueJS?

I have a component called blogPost (Component A) that is imported in another component named B. When a button in Component B is clicked, Component A opens in a modal. There are two different use cases for this scenario. 1. One case requires passing 2 prop ...

How can I use the form's restart() method in React-Final-Form to clear a MUI TextField input and also capture the event at the same time?

When I use form.restart() in my reset button, it resets all fields states and values based on my understanding of the Final-Form. The reset method triggers and clears all fields in the form, and I can capture the event in the autocomplete. However, I am fa ...