角度 util 函数的类型推断

问题描述 投票:0回答:1

我目前正在 Angular 中工作,我的 http 客户端返回

Observable<HttpResponse<T>>
。我正在尝试创建一个 util 函数来包装它并返回一个
Promise<T>

  const response = await baseResponseHandler(this.api.getAccountInfo('response'); //response is unknown

这是 util 函数:

export async function baseResponseHandler<
  K,
  T extends Observable<HttpResponse<K>>,
>(arg: T): Promise<K> {
  const value = await firstValueFrom(arg); //rxjs Observable -> Promise
  if (value.ok) {
    return value.body;
  }
  return value.body;
}

为什么它不能正确推断类型?

angular typescript rxjs observable typescript-generics
1个回答
0
投票
export async function baseResponseHandler<K>(
 arg: Observable<HttpResponse<K>>
): Promise<K> {
  const value = await firstValueFrom(arg);
  if (value.ok) {
    return value.body;
  }
  return value.body;
}

现在当你打电话时

const response = await baseResponseHandler<myType>(this.api.getAccountInfo('response');

我希望这对您有帮助。干杯🥂

© www.soinside.com 2019 - 2024. All rights reserved.