如何为已定义的接口分配值?

时间:2018-09-24 18:20:22

标签: typescript interface

我为试图构建客户端的响应定义了接口,我看到data的响应来自后端,因此现在我正尝试为接口对象分配值,而该对象未定义。不确定为什么会引起这个问题吗?

main.ts

  private async specialtyAccountBalanceResponse(@Body()data: IAccountBalanceSdkResult): Promise<any> {
      const saveDetails = {} as ICacheRequest;
      const specialtyResponse = {} as IGetAccountBalanceResponse;

      if (!data.Details && data.Header.StatusCode !== "0000") {
          return data.Header;
      }
      specialtyResponse.details.lineOfBusiness = "SPec";
      specialtyResponse.details.balanceAccount = data.Details.balanceAccount;
      return specialtyResponse;
  }

interface.ts

export interface IGetAccountBalanceResponse {
    header: any;
    details: IGetAccountBalanceDetails;
}

export interface IGetAccountBalanceDetails {
    lineOfBusiness: string;
    balanceAccount: string;
    payment: IPaymentIndicator;
}

export interface IPaymentIndicator {
    recentPaymentIndicator: string;
    recentPaymentAmount: string;
    achAuthRequiredInd: string;
}

2 个答案:

答案 0 :(得分:0)

您宁愿定义一个类而不是一个接口:

export class IGetAccountBalanceResponse {

    constructor(props?) {
       this.header = props.header;
       this.details = props.details;
    }

    public header: any;
    public details: IGetAccountBalanceDetails; 
}

然后您可以像这样实例化它:

const balance = new IGetAccountBalanceResponse()

const balance = new IGetAccountBalanceResponse(data)

这也可行,但除非有充分的理由,否则不应该这样做

const balance: IGetAccountBalanceResponse = {} as any;

接口不应用于实例化对象,而应用于定义其类型。

如果使用诸如eslint之类的linter(我强烈建议这样做),则在编译之前会弹出该错误。

在这里您可以尝试: http://www.typescriptlang.org/play/

Here are the official docs on it

Here is a working example

答案 1 :(得分:0)

在您的示例中,您创建一个空对象:

const specialtyResponse = {} as IGetAccountBalanceResponse;

然后,您尝试访问它的属性:

specialtyResponse.details.lineOfBusiness = "SPec";

details从未实例化,因此为undefined。因此,您无法访问其属性lineOfBusiness

一种解决方案是使用@undefinedMayNotBeNull建议的类。另一个方法是在访问属性之前先设置specialtyResponse.details

specialtyResponse.details = {} as IGetAccountBalanceDetails;

这是一个可行的示例:

interface IGetAccountBalanceResponse {
    details: IGetAccountBalanceDetails;
}

interface IGetAccountBalanceDetails {
    lineOfBusiness: string;
    balanceAccount: string;
}

const specialtyResponse = {} as IGetAccountBalanceResponse;
specialtyResponse.details = {} as IGetAccountBalanceDetails;

specialtyResponse.details.lineOfBusiness = "SPec";
specialtyResponse.details.balanceAccount = "Test";

Try it on TypeScript Playground


更新

specialtyResponse可能是错字。您是说specialityResponse吗?