我正在使一个Angular 组件依赖于API响应. 我是从API响应中得到这些的.

  1. 当没有错误的时候

    数据:{ 状态:字符串; 数据:编号; }

  2. 当出现错误时,我会得到这个.

    数据:{ 状态:字符串; 错误:字符串; 消息:字符串; }

正如我们所看到的,状态是很常见的,我try 实现了这一点.

interface ApiModel {
  Status: string;
}

interface DataModel extends ApiModel {
  Data: number;
}
interface ErrorModel extends ApiModel {
  ErrorCode: string;
  Message: string;
}

我正在try 使用打字脚本为它提供一个选项,其中它可以是任一类型,然后将该类型也传递给它的响应.

我不想在这里使用可选类型,因此我面临着这些问题.

我所期待的是,

if (typeof Response === DataModel){
Response: DataModel;
// Other code
}
else {
Response:ErrorModel;
// Other code
}

此处的API调用

getReminder(reminderId: number) {
    const API_URL = `${this.BASE_URL}users/${this.userId}/reminders/${reminderId}`;
    return this.httpClient.get<ErrorModel | DataModel>(API_URL, this.options).pipe(
      map((data: ErrorModel | DataModel) => {
        return data;
      })
    );
  }

推荐答案

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

isDataModel(response: ApiModel): response is DataModel {
  return response.Status === 'success';
}

getReminder(reminderId: number): Observable<DataModel | ErrorModel> {
  const API_URL = `${this.BASE_URL}users/${this.userId}/reminders/${reminderId}`;
  return this.httpClient.get<ApiModel>(API_URL, this.options).pipe(
    map((response: ApiModel) => {
      if (isDataModel(response)) {
        const responseData: DataModel = response as DataModel;
        return responseData;
      } else {
        // ErrorModel handling
        const errorResponse: ErrorModel = response as ErrorModel;
        throw errorResponse;
      }
    })
  );
}

接口可以像以前一样

interface ApiModel {
  Status: string;
}

interface DataModel extends ApiModel {
  Data: number;
}

interface ErrorModel extends ApiModel {
  ErrorCode: string;
  Message: string;
}

如果有任何问题或需要澄清的地方,请告诉我.

Typescript相关问答推荐

Typescript如何从字符串中提取多个文本

无需刷新即可让现场访客逆变

React-Native运行方法通过监听另一个状态来更新一个状态

node—redis:如何在redis timeSeries上查询argmin?

如何判断输入是否是TypeScript中的品牌类型?

如果一个变量不是never类型,我如何创建编译器错误?

类型脚本泛型最初推断然后设置

类型,其中一条记录为字符串,其他记录为指定的

ANGLING v17 CLI默认设置为独立:延迟加载是否仍需要@NgModule进行路由?

如果数组使用Reaction-Hook-Form更改,则重新呈现表单

是否可以判断某个类型是否已合并为内部类型?

RXJS将对键盘/鼠标点击组合做出react

ANGLE订阅要么不更新价值,要么不识别价值变化

打字错误推断

当数组类型被扩展并提供标准数组时,TypeScrip不会抱怨

如何从上传文件中删除预览文件图标?

使用本机 Promise 覆盖 WinJS Promise 作为 Chrome 扩展内容脚本?

为什么 TypeScript 类型条件会影响其分支的结果?

使用嵌套属性和动态执行时,Typescript 给出交集而不是并集

有没有办法从不同长度的元组的联合中提取带有类型的最后一个元素?