Enhance nested IFELSE statements in TypeScript

While working on a personal project, I find myself dealing with multiple conditions. I'm wondering if there's a more efficient way to handle this as the current code appears somewhat messy with all these IFELSE statements.

public static async handleLiquidations(request : Request, response: Response){
    const id = request.params.code;
    const {month, year , ...optional} = request.body;
    let msg = "";
    if(!!month && !!year ){
      const liquidationsController = new LiquidationsController();
      if(optional.amountToReport){
        liquidationsController.updateAmountToReport(month,year,optional.amountToReport);
      } else {
        msg += "missing amount to report";
      } if (optional.comments) {
        liquidationsController.updateComments();
      } else {
        msg += "missing comments";
      } if (optional.startDate) {
        liquidationsController.updateStartDate();
      } else {
        msg += "missing start date";
      } if (optional.endDate) {
        liquidationsController.updateEndDate();
      } else {
        msg += "missing end date";
      }

      response.status(200);
      response.json({optional, msg});
      return;
    } else {
      errorResponse(response,403,"Required arguments are missing")
    }
  }

Answer №1

Consider condensing the error messages into a single if statement:

if (!optional.amountToReport || !optional.comments || !optional.startDate || !optional.endDate) {
   msg = `Insufficient data: ${JSON.stringify(optional)}`;
} else {
  liquidationsController.updateAmountToReport(month,year,optional.amountToReport);
    liquidationsController.updateComments();
    liquidationsController.updateStartDate();
    liquidationsController.updateEndDate();
}

This approach streamlines your conditional logic.

You might also want to create a function that checks for null values in the optional object. Check out this answer for more insights.

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

Seeking help with a Javascript regex inquiry

I am currently utilizing JavaScript regex for the following task: I have gathered the HTML content from a page and stored it within a string. Now, I aim to identify all URLs present on this page. For instance, if the document includes-- <script src = ...

Determination of function return type based on the presence of an optional argument

I am attempting to design a function that will have a return type based on whether an optional parameter (factory) is provided or not If the factory parameter is passed, then the return type should match the return type of the factory Otherwise, it shoul ...

Utilizing ng-repeat to iterate over a nested array

I need help figuring out how to properly loop through a JSON array and its ingredients/directions array using ng-repeat. The current method I have attempted is not working as expected. Any suggestions or advice would be greatly appreciated! Thank you. Con ...

What is a more organized approach to creating different versions of a data type in Typescript?

In order to have different variations of content types with subtypes (such as text, photo, etc.), all sharing common properties like id, senderId, messageType, and contentData, I am considering the following approach: The messageType will remain fixed f ...

When an event occurs, have Express make an HTTP call to Angular

In the process of developing an Angular application, I am working on a feature that will enable around a thousand users to connect simultaneously in order to book tickets. However, I only want a specific number of them, let's call it "XYZ", to access ...

How to load a table file in JavaScript synchronously

I came across this particular method for accessing a local text file. However, I am facing an issue as I do not want the file to be read asynchronously. My goal is to have the function read the file and return the output as a string variable instead. The ...

Can JavaScript executed within a web browser have the capability to manipulate files on the underlying host system's file system?

Is it possible to programmatically move files or folders from a website using code? I am aware that with Python and Node.js, this can be achieved through the OS, path, and fs modules. Can JavaScript running in a website also handle file management tasks ...

Typescript: The argument provided, which is of type 'number', cannot be matched to a parameter of type 'string'

Need a solution to remove decimals from a number in TypeScript. I have tried using the parseInt method but encountered the following error: Argument of type 'number' is not assignable to parameter of type 'string' Code: function test ...

How can VueX be leveraged to add an item to an array and also delete an item from the same array?

https://stackblitz.com/edit/vue-script-setup-with-vuex-gfjaff?file=src/components/UserProfile.vue I'm currently working on a feature where I can input a name into a dispatch function and have it added to an array. Eventually, I plan to include a text ...

script loop causing an embedded form

While trying to include a Hubspot embedded form on a page using a script, I encountered an issue. I utilized onMounted to ensure the form is displayed correctly. However, upon leaving and re-entering the component where the form is located, an additional b ...

What is the process of declaring a variable within a class in TypeScript?

When setting up an instance variable inside my Angular component like this: @Component({ selector: 'app-root', templateUrl: './app.component.html', //template: `` styleUrls: ['./app.component.css'] }) export class AppCo ...

Text in ion-searchbar should be clear

I currently have a search bar implemented on my page <div id="search"><ion-searchbar [(ngModel)]="searchQuery" (change)="onChange($event)" (ionClear)="onCancel($event)" (ionInput)="onInput($event)" debounce="1"></ion-searchbar></div&g ...

Generating a stacked array using JavaScript

I have an original two-dimensional array representing the full budget for each year, as shown below: budget = [['2001-01-01', 100], ['2001-01-02', 110], ... , ['2001-12-31', 140]] Now I want to create subarrays of the budget ...

"Double the Data: A D3.js JSON Tale of Two Creators

I found inspiration from this example: http://bl.ocks.org/mbostock/1062288 to create a collapsible Force Layout. One challenge I'm facing is how to display a graph where a single node is connected to two parent nodes. father father | | ...

Mixing TypeScript generic types loosely

Let's explore a simple example of typescript mixins: import { Observable, of } from 'rxjs'; class Service<TDataType> { public foo(f: TDataType): Observable<TDataType> { return of(f); } } type GConstructor<T = {}> = new ...

Object-oriented programming in JavaScript allows for the passing of variables to a parent class using $

I am attempting to transfer variables from an XML file to the parent class in JavaScript. The code follows Object-Oriented Programming principles, with a class named "example" and a method called getData(). The issue I'm encountering is that the AJAX ...

Comparing nestableSortable with the Nestable JavaScript library

I am in the process of developing a navigation menu editor that consists of multiple nested, sortable forms. My goal is to submit all the form data in one comprehensive JSON data blob. After researching, I have narrowed down my options to two libraries: n ...

Different ways to activate the system bell in Node.js

Currently, I have a custom nodejs script running for an extended period and I'm seeking a way to receive a notification once the script finishes its execution. Is there a method in nodejs that can be used to activate the "System Bell" alert? ...

What could be preventing my Express error handler from being invoked after running lint on my code?

I'm currently working on an Express app that features a custom error handler. The code for the error handler is as follows: app.use((err: Error, _req: express.Request, res: express.Response) => { console.log(err) // ...send back a well formatt ...

Transitioning from using a jQuery get request to utilizing Vue.js

Looking to transition from JQuery-based js to Vue as a newcomer to JavaScript. Seeking guidance on making a get request and displaying the retrieved data. What approach would you recommend for this task? Here's the HTML snippet: <div> <di ...