类型'""|中不存在属性"错误" 许<任何>"

tof*_*ofu 9 typescript angular

我正在尝试按照Angular 指南为服务添加一些错误处理.

相关片段:

private handleError (error: Response | any) {
  // In a real world app, you might use a remote logging infrastructure
  let errMsg: string;
  if (error instanceof Response) {
    const body = error.json() || '';
    const err = body.error || JSON.stringify(body);
    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  } else {
    errMsg = error.message ? error.message : error.toString();
  }
  console.error(errMsg);
  return Observable.throw(errMsg);
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到一个TypeScript错误:

error TS2339: Property 'error' does not exist on type '"" | Promise<any>'. Property 'error' does not exist on type '""'.

我可以理解为什么会发生这种情况 - error.json()返回a Promise<any>然后后续行将body.error无效,因为没有error属性.但是,它似乎应该期望从中返回JSON对象.json().为什么会这样,而我错过了Angular指南不是什么?

Mar*_*son 25

同样的事情发生在我身上.无法导入Response对象时会发生这种情况.

import { Response } from '@angular/http';
Run Code Online (Sandbox Code Playgroud)

  • 啊谢谢你!我的IDE正在识别Response但它不是Angular的.这完全有道理. (4认同)