Search code examples
angulartypescriptangular-services

Getting "Property info and results doesn't exist on type Response"


I have created a service to make an HTTP request to fetch users. But, I'm getting an error while modifying the API response. I tried everything and can't figure out the solution. Here's is the image of the code:

Code Image

Here is the code inside user.service file:

export class UserService {
  private readonly apiUrl: string = 'https://randomuser.me/api';

  constructor(private http: HttpClient) {}

  getUsers(size: number = 10): Observable<any> {
    return this.http
      .get<any>(`${this.apiUrl}/?results=${size}`)
      .pipe(map((response) => this.processResponse(response)));
  }

  getUser(uuid: number = 1): Observable<any> {
    return this.http
      .get<any>(`${this.apiUrl}/?uuid=${uuid}`)
      .pipe(map((response) => this.processResponse(response)));
  }

  private processResponse(response: Response): Response {
    return {

// ERROR 1 - Object literal may only specify known properties, and 'info' does not exist in type 'Response'.

//ERROR 2 - Property 'info' does not exist on type 'Response'

      info: { ...response.info },

// ERROR 3 - Property 'results' does not exist on type 'Response'
      results: response.results.map(
        (user: any) =>
          <User>{
            uuid: user.login.uuid,
            firstname: user.name.first,
            lastname: user.name.last,
            email: user.email,
            username: user.login.username,
            gender: user.gender,
            address: `${user.location.street.name} ${user.location.street.number} , ${user.location.city}, ${user.location.state}, ${user.location.country} `,
            dob: user.dob.date,
            phone: user.phone,
            imageUrl: user.picture.medium,
            coordinates: {
              latitude: +user.location.coordinates.latitude,
              longitude: +user.location.coordinates.longitude,
            },
          }
      ),
    };
  }
}

And here is the code inside Response interface

import { Info } from './info';

export interface Response {
  info: Info;
  results: any[];
}

Solution

  • You need to import your Response interface at the top of your TypeScript file:

    import { Response } from '../path-to-your-interface';
    

    If you skip the import, the built-in Response type will be used, which is not the correct type for your case.

    I would recommend to use a different name for your interface, so TypeScript will throw an error if you forget to import. This will avoid such issues.