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?
>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.