Home > Net >  How can I return a specific object from a generic function?
How can I return a specific object from a generic function?

Time:11-17

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:

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?

CodePudding user response:

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.

CodePudding user response:

try this by defining type in TS : 

type ET = {
      id: number;
      value: string;
    };


getData(): Observable<ET[]> {
    return of([
      { id: 1, value: "test1" },
      { id: 2, value: "test2" },
    ]);
  }
  • Related