Typescript: Unfiltering a string array

Seeking assistance with TypeScript syntax as a beginner.

I'm struggling to refactor this code in order to retrieve the full list of serviceBranches. Currently, there is filtering and mapping resulting in only one serviceBranch being returned from our API. I have attempted removing filters without success. Can someone guide me on how to fetch all serviceBranches by eliminating the correct filters?

Thank you in advance.

public async personNews(serviceBranch?: string[]): Promise<INews> {
    const fetchResult: IPersonNewsFetchResultEntry[] = await this._get('api/person/news/', newsSchema, true) as IPersonNewsFetchResultEntry[];
    const serviceBranches: string[] = (serviceBranch !== undefined ? serviceBranch : fetchResult.filter((entry: IPersonNewsFetchResultEntry, index: number, array: IPersonNewsFetchResultEntry[]): boolean => { 
      return entry.niveauID === NewsLevel.ServiceBranch && array.findIndex((value: IPersonNewsFetchResultEntry): boolean => {
        return entry.unitID === value.unitID;
      }) === index;
    }).map((entry: IPersonNewsFetchResultEntry): string => {
      return entry.unitID;
    }));

Answer №1

Why is explicit typing necessary in all instances?

Could it be due to

this._get('api/person/news/', newsSchema, true);
returning a type of any?

By making some adjustments and removing specific types, the code becomes easier to understand

public async fetchNewsForPerson(serviceBranch?: string[]): Promise<INews> {
  const data = await this._get('api/person/news/', newsSchema, true);

  let selectedServiceBranches: string[] = [];

  if(serviceBranch) {
    selectedServiceBranches = serviceBranch;
    return;
  }

  selectedServiceBranches = data.filter((entry, index, array) => { 
    return entry.niveauID === NewsLevel.ServiceBranch
        && array.findIndex(({unitID}) => entry.unitID === unitID) === index;
    }).map(entry => entry.unitID)
}

Answer №2

This function appears to be quite complex and difficult for a human to interpret easily. Let's improve its readability:

public async fetchPersonNews(serviceBranch?: string[]): Promise<INews> {
  const result: IPersonNewsFetchResultEntry[] = (await this._get(
    'api/person/news/',
    newsSchema,
    true,
  )) as IPersonNewsFetchResultEntry[]
  const branches: string[] =
    serviceBranch !== undefined
      ? serviceBranch
      : result
          .filter(
            (
              entry: IPersonNewsFetchResultEntry,
              index: number,
              array: IPersonNewsFetchResultEntry[],
            ): boolean => {
              return (
                entry.niveauID === NewsLevel.ServiceBranch &&
                array.findIndex(
                  (value: IPersonNewsFetchResultEntry): boolean => {
                    return entry.unitID === value.unitID
                  },
                ) === index
              )
            },
          )
          .map((entry: IPersonNewsFetchResultEntry): string => {
            return entry.unitID
          })

It is now more apparent that the result is initially filtered, and then the selected items are mapped to extract just their unitID.

Without additional context, it is unclear what specific logic or data structure you require. You can adjust the code accordingly - remove the filter() call for all results, eliminate the map() call to return entire objects instead of just unitID, or modify the filtering criteria within the filter method.

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

Methods for invoking a JavaScript function from TypeScript within an Angular2 application

Hey there! I'm looking to execute a regular JavaScript function from a TypeScript file. Let's say I have a JavaScript file called test.js and it's been imported into the index.html of my application. Now, I want to invoke the test() functi ...

A powerful trio: Axios, Typescript, and Promises

I am facing a TypeScript dilemma. I have a REST method that is being called within my http library by Vue action. I want the resolve() method to return the typed array, but if I do not convert it within the action.ts "then" method, I get a '.length do ...

Setting up a Variable with an Object Attribute in Angular

I am attempting to create a variable that will set a specific property of an object retrieved through the get method. While using console.log in the subscribe function, I am able to retrieve the entire array value. However, as a beginner, I am struggling ...

SQL Exception: The value for the first parameter is not defined

I'm encountering an issue with a SqlError while trying to retrieve data from my database. It seems like the problem is within my fetchData function where I might not be passing the two parameters (startDate and endDate) correctly. The specific SqlErr ...

Encountering difficulty invoking a component method from d3's call() function

My current setup involves using D3 to drag and drop links in the following manner: .call(d3.drag() .on("start", linkDragStart) .on("drag", linkDragging) .on("end", linkDragEnd)); Recently, I decided to extract this functionality into a separate met ...

What is the purpose of specifying the props type when providing a generic type to a React functional component?

When utilizing the @typescript-eslint/typedef rule to enforce type definitions on parameters, I encountered an issue with generically typing a React.FC: export const Address: React.FunctionComponent<Props> = (props) => ( An error was thrown st ...

What is the best way to showcase two different arrays' data in a single Angular view?

I have 2 different arrays retrieved from an API with no common FK or any other identifier. Even though my TypeScript code produces the expected results, the view remains blank. The debugging results are provided as comments in the code snippet below: ngO ...

Angular rxjs Distinctions

Coming from AngularJS to Angular, I'm still trying to wrap my head around rxjs observable. For example: User.ts export class User { id?:any; username:string; password:string; } Using <User[]> myUser(header: any) { const url = `${this.mainUr ...

What steps should I follow to utilize a JavaScript dependency following an NPM installation?

After successfully installing Fuse.js using npm, I am having trouble using the dependency in my JavaScript code. The website instructions suggest adding the following code to make it work: var books = [{ 'ISBN': 'A', 'title&ap ...

The type definition file for 'jest' cannot be located, despite the fact that jest has been successfully installed

SOLUTION STRATEGY: If you encounter a similar issue and are looking for a more comprehensive solution rather than quick fixes, consider recreating the repository. While it involves more effort initially, it can prevent future issues. In my case, the repos ...

Interacting between Angular Child and Parent components

I am facing an issue where I am trying to emit an event from a child component and display it in the parent HTML, but it doesn't seem to be working. Below is my code: ParentComponent.ts @Component({ selector: 'app-parent', templateUrl: ...

New feature in Next.js 13: Utilizing a string within className

Looking for a way to dynamically generate radio buttons in Next.js using a list of strings? Utilizing Tailwind CSS classes, you can modify the appearance of these buttons when checked by leveraging the peer/identifier classname. But how do you include th ...

Creating a React component with multiple prop types using Typescript

In this particular component, the requirement is to input a config object that can be of two types - either an object containing a "name" property (which should be a string), or a boolean value indicating that the config object has not been set yet. type C ...

Trouble with selectionChange event in mat-select component in Angular 13

I'm having trouble getting the selectionChange event to fire in my mat-select when the value is changed. html file <mat-select (selectionChange)="changeCategory()"> <mat-option *ngFor="let category of categ ...

Error: Promises must be managed correctly

I've been working on a timer-based function that is supposed to run once a week and create almost identical copies of existing documents. However, every time I try to execute it, I encounter the error message "Promises must be handled appropriately." ...

I want to use Angular and TypeScript to play a base64 encoded MP3 file

I am attempting to play a base64 encoded mp3 file in an Angular application. I have a byteArray that I convert to base64, and it seems like the byte array is not corrupted because when I convert it and paste the base64 string on StackBlitz https://stackbli ...

Testing Angular 2 components with material icons and images

Recently, I finished creating a unique component that showcases an image, material icons, and a custom directive known as ticker. This directive allows for scrolling text if it exceeds the width of the element. https://i.stack.imgur.com/GpDSr.png My next ...

Having issues with using the class selector in SVG.select() method of the svg.js library when working with TypeScript

Exploring the capabilities of the svg.js library with typescript has presented some challenges when it comes to utilizing CSS selectors. My goal is to select an SVG element using the select() method with a class selector. In this interactive example, this ...

Time taken for a webpage to finish loading

Is there a way to programmatically obtain the page load time in an Angular application? Situation: On my dashboard page, various components are making multiple calls. I want to calculate the overall time it takes to load all widgets on the page. ...

Utilize useState and useEffect to efficiently sort through an item list based on its current state

I am currently working on an application where I have a list of items and I need to create a details page for each item when clicked. I am facing some challenges in implementing this functionality using useState, useEffect, and typescript. I have previousl ...