0

Having the following shared

export class DataStorageService {

  constructor(private http: HttpClient) {}

  fetchAll(dataType: string) {
    let apiEndpoint = environment.config.urlLogin + '/api/' + dataType;

    return this.http.get(apiEndpoint);
  }

and using it here

export class InvoiceListComponent implements OnInit {

invoices: Invoice[] = [];

  constructor(private ds: DataStorageService) {
  }

  ngOnInit(): void {
    this.fetchInvoices();
  }

  fetchInvoices() {
    this.ds.fetchAll('invoices').subscribe((responseData) => {
      if (responseData.hasOwnProperty('hydra:member')) {
        //reaching here
        // but this throws compile error
        this.invoices = responseData['hydra:member'];
      }

    })
  }

I get the following compile error with Angular 12:

Element implicitly has an 'any' type because expression of type '"hydra:member"' can't be used to index type 'Object'. Property 'hydra:member' does not exist on type 'Object'.

Honestly I do not understand at all why this is showing up. I mean I even reach the positive check whether this property exists?

1

1 Answer 1

2

Easy fix! Declare an interface specifying the type of data you are expecting to get:

// interface.ts
export interface MyType {
    "hydra:member": string
}

assign this type to the returned data:

// service
import { MyType } from './interface.ts';
...
return this.http.get(apiEndpoint) as Observable<MyType>;

I think this should work if I did not forget anything!

Sign up to request clarification or add additional context in comments.

8 Comments

thanks a lot, will try that. but could you explain why this error occurs although I specifically get an object and check on existence of the property before accessing it?
Yes, it's a typescript thing. You need to specify types in order for Typescript not to throw "errors". The error you got just said that it is infering an any type, in order for it to disappear you can just specify the type of data you are expecting to retrieve. By doing so, you will also remove the need for checking the hasOwnProperty, as you know your type has the property already. If it could be null, specify it in the interface.
and just in case I wouldn't (perfectly) know? isn't there any way to "work around" this? or will I have to define then an "generic enough" interface?
Yes, the "any" type can be a friend of yours if you do not know the exact type. However, try to avoid it as all the typescript benefits are erased by its usage...
Yes I believe so.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.