请考虑以下泛型函数:
public getData<T>(url: string): Observable<T> {
return this.httpClient.get<T>(url);
}
如何返回一个硬编码的模拟对象数组以便测试函数(例如,因为远程API尚未实现)?
我想退回这个:
return of([{id: 1, value: 'test1'}, {id: 2, value: 'test2'}]);
但我得到这个错误:
TS 2322:类型“可观察〈{ id:数字;值:字符串; }[]〉'不能赋值给类型' Observable '。 键入“{ id:number; value:字符串;}[]'无法指派给型别' T '。 “T”可以用与“{ id:数字;值:字符串; }[]“。
有没有办法做到这一点?
2条答案
按热度按时间3b6akqbq1#
就我所知,
as any as T
也能正常工作。ma8fv8wu2#