【问题标题】:Is it valid to return null from a didReceiveResponse callback?从 didReceiveResponse 回调返回 null 是否有效?
【发布时间】:2020-04-25 03:16:54
【问题描述】:

我在扩展 RESTDataSource 的类上有一个 didReceiveResponse 回调,如果响应状态为 404,我将在其中返回 null。由于输入了 RESTDataSource.didReceiveResponse,这似乎是无效的。

  async didReceiveResponse<T>(res: Response, req: Request): Promise<T | null> {
      if (res.status === 404) {
        return null;
      }

      return super.didReceiveResponse(res, req);
  }

这是我在使用 --strict-null-checks 时遇到的 Typescript 错误

TS2416: Property 'didReceiveResponse' in type 'APIDataSource' is not assignable to the same property in base type 'RESTDataSource<ResolverContext>'.
  Type '<T>(res: Response, req: Request) => Promise<T | null>' is not assignable to type '<TResult = any>(response: Response, _request: Request) => Promise<TResult>'.
    Type 'Promise<TResult | null>' is not assignable to type 'Promise<TResult>'.
      Type 'TResult | null' is not assignable to type 'TResult'.
        Type 'null' is not assignable to type 'TResult'.

有没有办法在不禁用编译器或严格的空检查的情况下在返回 null 的同时解决这种输入问题?

【问题讨论】:

    标签: typescript apollo apollo-server apollo-datasource-rest


    【解决方案1】:

    看看RESTDataSource.ts#L100这个apollo-datasource-rest包的源代码。

    didReceiveResponse方法的源码为:

    protected async didReceiveResponse<TResult = any>(
        response: Response,
        _request: Request,
    ): Promise<TResult> {
        if (response.ok) {
          return (this.parseBody(response) as any) as Promise<TResult>;
        } else {
          throw await this.errorFromResponse(response);
        }
    }
    

    他们使用这样的类型断言:

    return (this.parseBody(response) as any) as Promise<TResult>;
    

    所以,如果您确定 null 值正是您想要的,您也可以这样做

    例如

    SomeDataSource.ts:

    import { RESTDataSource } from 'apollo-datasource-rest';
    import { Response, Request } from 'apollo-server-env';
    
    class SomeDataSource extends RESTDataSource {
      protected async didReceiveResponse<TResult>(res: Response, req: Request): Promise<TResult> {
        if (res.status === 404) {
          return (null as any) as Promise<TResult>;
        }
    
        return super.didReceiveResponse<TResult>(res, req);
      }
    }
    

    tsconfig.json:

    "strictNullChecks": true /* Enable strict null checks. */,
    

    【讨论】:

      猜你喜欢
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      相关资源
      最近更新 更多