Допустимо ли возвращать значение null из обратного вызова didReceiveResponse? - PullRequest
0 голосов
/ 07 января 2020

У меня есть 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 без отключения компилятора или строгой проверки нуля

1 Ответ

0 голосов
/ 08 января 2020

Посмотрите на 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. */,
...