typescript 如何从泛型函数返回特定对象?

ih99xse1  于 2022-11-18  发布在  TypeScript
关注(0)|答案(2)|浏览(145)

请考虑以下泛型函数:

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:数字;值:字符串; }[]“。
有没有办法做到这一点?

3b6akqbq

3b6akqbq1#

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

就我所知,as any as T也能正常工作。

ma8fv8wu

ma8fv8wu2#

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" },
    ]);
  }

相关问题