这个“隐式”具有类型,是否没有类型注释?

时间:2018-10-15 14:38:50

标签: javascript typescript this

我正在调用函数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"
        };
    }

1 个答案:

答案 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"
    };
}