我正在调用函数this.buildSingleRequestBody
,它抛出错误,该隐含类型为任何类型,没有类型注解,不确定什么实现错误。
main.ts
private buildRequestArray(specialtyMembers: ISpecialtyInfoObj[],
request: ICombinedAccountBalanceRequest): IRequestURL[] {
const specialtyUrl = urlConfig.specialtyBaseUrl + "payments/getAccountBalance";
const serviceContext = request.header.serviceContext;
const requestArray: IRequestURL[] = specialtyMembers.map(function(member) {
const body: any = this.buildSingleRequestBody(member, serviceContext);
return {url: specialtyUrl, body};
});
return requestArray;
}
private buildSingleRequestBody(specialtyMember: ISpecialtyInfoObj, serviceContext: IServiceContext) {
return {
"header": {
serviceContext
},
"specialtyId": specialtyMember.Id || "78988716",
"specialtySource": specialtyMember.specialtySource || "HBS"
};
}
答案 0 :(得分:3)
function
不会从声明上下文中捕获this
,而是this
由调用者决定。由于调用function
时使用map
,因此匿名函数内的this
将不会引用该类。由于map
并未明确声明它将传递给函数的this
,因此this
的类型将隐式为匿名函数内部的任何类型,因此会出现错误。
请改用箭头函数,因为它将捕获声明this
private buildRequestArray(specialtyMembers: ISpecialtyInfoObj[],
request: ICombinedAccountBalanceRequest): IRequestURL[] {
const specialtyUrl = urlConfig.specialtyBaseUrl + "payments/getAccountBalance";
const serviceContext = request.header.serviceContext;
const requestArray: IRequestURL[] = specialtyMembers.map((member) => {
const body: any = this.buildSingleRequestBody(member, serviceContext);
return {url: specialtyUrl, body};
});
return requestArray;
}
private buildSingleRequestBody(specialtyMember: ISpecialtyInfoObj, serviceContext: IServiceContext) {
return {
"header": {
serviceContext
},
"specialtyId": specialtyMember.Id || "78988716",
"specialtySource": specialtyMember.specialtySource || "HBS"
};
}