我为试图构建客户端的响应定义了接口,我看到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;
}
答案 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/
答案 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
吗?