Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I return a specific object from a generic function?

Consider this generic function:

  public getData<T>(url: string): Observable<T> {
    return this.httpClient.get<T>(url);
  }

How can I return a hardcoded mock object array in order to test the function (for example because the remote API has not been implemented yet)?

I would like to return this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

return of([{id: 1, value: 'test1'}, {id: 2, value: 'test2'}]);

but I am getting this error:

TS2322: Type ‘Observable<{ id: number; value: string; }[]>’ is not assignable to type ‘Observable’.   Type ‘{ id: number; value: string; }[]’ is not assignable to type ‘T’.     ‘T’ could be instantiated with an arbitrary type which could be unrelated to ‘{ id: number; value: string; }[]’.

Is there a way to achieve this?

>Solution :

return of([{id: 1, value: 'test1'}, {id: 2, value: 'test2'}] as unknown T); 

Does the trick. Also as any as T should work as far as I know.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading