4
votes

ERROR in src/app/new-applicant/new-applicant.service.ts(35,65): error TS2345: Argument of type '{ reportProgress: boolean; observe: string; headers: HttpHeaders; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'. Types of property 'observe' are incompatible. Type 'string' is not assignable to type '"body"'.

    public generateHeaders()
    {
        let access=JSON.parse(sessionStorage.getItem("meta_info")).access
        // access=access.access;
        console.log(access)
        var headers_object = new HttpHeaders().set("Authorization", "Bearer " + access);
        const httpOptions = {
            reportProgress:true,
            observe:'events',
            headers: headers_object
        };
        return httpOptions
    }

service

  public registerNewApplicant(data)
  {
    return this.http.post(environment.baseURL+"applicant/",data,this.jwtTokenGenerator.generateHeaders())
  }
3

3 Answers

5
votes

Use as const to force TypeScript to infer the type of observe as the literal type "events" instead of string:

observe: 'events' as const,

Each method in HttpClient has a bunch of overloads which expect observe to be one of the following: "body", "events", "response".

TypeScript by default infers type of string literals as string, except in some contexts such as initializing a const or readonly fields. The return type of generateHeaders ends up being

{ reportProgress: boolean; observe: string; headers: HttpHeaders; }

The info about observe being "events" is lost, so this value does not match any of the overloads.

3
votes

Cast it to 'events'

observe: 'events' as 'events'
0
votes

I'm not a typescript expert, but if you supply the generateHeaders method with a return type in the signature, it should fix your error.

public generateHeaders(): any {
  ...
}