0

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

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

      return super.didReceiveResponse(res, req);
  }

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

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有没有办法在不禁用编译器或严格的空检查的情况下在返回的同时解决这种打字问题?

4

1 回答 1

0

看看这个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. */,
于 2020-01-08T06:09:02.340 回答