The reason behind my struggle with mapping API responses to an Interface in Angular

Hello everyone, I am currently working on mapping some API responses from The Muse API to an APIResponseInterface that I have created. Here's a snippet of my code:

Service that sends the request:

getJobs(page: number): Observable<APIResponseInterface>{
    return this.http.get<APIResponseInterface>(this.url + page)

  }

API Response Interface

export interface APIResponseInterface {
  page?: number,
  page_count?: number,
  items_per_page?: number,
  took?: number,
  timed_out?: boolean,
  total?: number,
  results: Array<JobInterface>
}

Upon receiving the items in the "results", I want to map them to this interface:


export interface JobInterface {
  contents: HTMLAllCollection,
  name: string,
  type?: string,
  publication_date?: Date,
  short_name?: string,
  model_type?: string;
  id? : number,
  locations: LocationInterface[]
  level: LevelsInterface[],
  company: CompanyInterface,
}

In my Angular component, I'm using the following function to map the results into an array of JobInterface:

this.jobsService.getJobs(1)
      .subscribe((response) => {
        this.jobs = response.results.map<JobInterface>(job => {{
          name: job.name

          }}
        )
        console.log(this.jobs)
      })

However, I am encountering errors such as:

TS2345: Argument of type '(job: JobInterface) => void' is not assignable to parameter of type '(value: JobInterface, index: number, array: JobInterface[]) => JobInterface'.

Can you please assist me in figuring out what mistake I might be making and the correct approach to resolve it?

Answer №1

Make sure to use parenthesis instead of curly braces for the return statement

this.jobs = response.results.map<JobInterface>(job => ({
            name: job.name
            ...
          })

If you opt for curly braces, remember to include a return statement.

this.jobs = response.results.map<JobInterface>(job => {
   return {
            name: job.name
            ...
          }
    }

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

Is it possible to alter the background color once the content of an input field has been modified?

I am working with an angular reactive form and I want to dynamically change the background color of all input fields when their value is changed. Some of these input fields are pre-populated and not required. I came across a potential solution on Stack Ove ...

Tips for adjusting a Bootstrap table to the size of the page it's on

app.component.html <html> <nav class="navbar navbar-expand-md"> <div class="container"> </div> <div class="mx-auto order-0"> <a class="navbar-brand mx-auto" href="#">GURUKULAM PRE-SCHOO ...

Preflight CORS error 403, yet my header is correctly set

Currently developing an Ionic app that communicates with an API on a web server for database operations. A similar project was completed in the past, and I copied the code from there, but it's not functioning as expected. Below are the headers config ...

What is the best way to deliver a downloaded document to a client using NodeJS Express?

I am facing an issue with downloading files from my FTP server using a button on my front-end website. The FTP server is password protected, and only I as the admin have access to the password. However, when the user clicks the download button, the file ge ...

Angular 10 is displaying a message indicating that a font has not been

I'm facing an error in my Angular project when trying to add a font to the SCSS file. How can I resolve this issue? style.scss: @import "~@angular/material/theming"; @include mat-core(); $PWP-primary: mat-palette($mat-indigo); $PWP-accent: ...

Can anyone provide a webpack configuration to package a webpack plugin together?

I'm in the process of developing a webpack plugin using typescript. Before I can publish it on NPM, I need to bundle the plugin code. However, I've encountered an exception stating that my plugin class is not a constructor. Below is the director ...

Error: The 'update' property cannot be found on the specified type

Starting a new AngularCli project and need to incorporate a Gauge chart. I've used the code from StackBlitz Angular Gauge Chart Example When I run ng serve --open, I encounter the following errors in the terminal: ERROR in src/app/gauge/gauge.comp ...

Mastering the usage of TypeScript union types with distinct internals

It's frustrating that in the example below, I encounter a typescript error despite the fact that the error is not logically possible to occur in the code. The function receives either Category1 or Category2 and when it returns the ComputedCategory, bo ...

Setting up Angular-CLI on a Windows 10 system

I encountered some challenges while trying to install angular-cli on my Windows 10 system. The issues revolved around Python dependencies and node-gyp, manifesting in error messages similar to the following: ><a href="/cdn-cgi/l/email-protection" ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

When executed, the Node application successfully compiles

I have a TypeScript application that runs smoothly in development mode using ts-node. However, after building the application, I encounter some unexpected warnings and errors. This is my tsconfig.json: { "compilerOptions": { "incremen ...

TS1316 Error: You can only have global module exports at the top level of the file

Encountering difficulties while trying to compile an older typescript project that I am revisiting. The build process is failing due to an issue with q. I suspect it may be related to the tsc version, but no matter which version I try, errors persist. Som ...

The mat-checkbox is failing to accurately reflect its checked state

This code snippet is from my .html file: <mat-checkbox [checked]="getState()" (change)="toggleState()">Example Checkbox</mat-checkbox> <br><br> <button mat-raised-button color="primary" (click)=" ...

Enhancing TypeScript Types with a custom method within an Angular 2 context

I am working on an Angular 2 project using the CLI. Currently, I am trying to add a custom method to the String type as shown below. interface String { customMethod(): number; } String.prototype.customMethod = function() { return 0; } Despite my ...

Showcase Ionic Validation - exhibit error messages reminiscent of material design

I've been working on a Login and Registration Page in Ionic 5. I wanted to showcase error messages beneath the input text field like shown in this example https://i.stack.imgur.com/d83ZV.png Thus, I integrated Angular Responsive Forms into my projec ...

The type '(props: Props) => Element' cannot be assigned to the type 'FunctionComponent<FieldRenderProps<any, HTMLElement>>' in React-final-form

I'm fairly new to using TypeScript, and I am currently working on developing a signUp form with the help of React-Final-Form along with TypeScript. Here is the code snippet that describes my form: import React from "react"; import Button from "@mater ...

Is Validators.required a necessity in Angular 2?

Is there a way to dynamically require a form field based on conditions? I created a custom validator, but the conditional variables passed to it remain static. How can I update these conditional values within the custom validator function? Is it possible t ...

Avoid displaying the value in Ant Design's autocomplete feature

Can someone assist me with clearing the auto complete placeholder or displaying only part of the label instead of the value after a user selects from a drop-down list? The current setup shows the unique ID as the value, which we want to keep hidden from en ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

Manipulate inherited CSS styles from an external source

Currently, I am working on creating a pagination using the NG-Bootstrap pagination component. However, I encountered an issue where I need to modify or specifically remove some CSS properties that are applied by default in the NG-Bootstrap library. Is ther ...