TS2769 No overload matches this call



  • I'm looking at a tutorial on the utubus, like adding token in response. There's a service where they get token

      get token (): string | null {
        const fbTokenExp = localStorage.getItem('fb-token-exp');
        if (fbTokenExp) {
          const expDate = new Date(fbTokenExp);
          if ( new Date > expDate ) {
            this.logout()
            return null
          }
          return localStorage.getItem('fb-token')
        }
        return null;
      }
    

    and intercept where the addition token occurs

    intercept(req: import("@angular/common/http").HttpRequest<any>,
                next: import("@angular/common/http").HttpHandler): import("rxjs").Observable<import("@angular/common/http").HttpEvent<any>> {
    
    if (this.auth.isAuthenticated()) {
      req = req.clone({
        setParams: {
          auth: this.auth.token
        }
      })
    }
    

    IDEA swears on this line

    auth: this.auth.token

    He says

    TS2769: No overload matches this call.   Overload 1 of 3, '(update: { headers?: HttpHeaders | undefined; context?: HttpContext | undefined; reportProgress?: boolean | undefined; params?: HttpParams | undefined; ... 6 more ...; setParams?: { ...; } | undefined; }): HttpRequest<...>', gave the following error.     Type 'string | undefined' is not assignable to type 'string'.       Type 'undefined' is not assignable to type 'string'.   Overload 2 of 3, '(update: { headers?: HttpHeaders | undefined; context?: HttpContext | undefined; reportProgress?: boolean | undefined; params?: HttpParams | undefined; ... 6 more ...; setParams?: { ...; } | undefined; }): HttpRequest<...>', gave the following error.     Type 'string | undefined' is not assignable to type 'string'.       Type 'undefined' is not assignable to type 'string'.

    I don't know how to fix it.



  • SetParams has a type:

    {
     [param: string]: string;
    }
    

    You're most likely to transmit a meaning that can be undefined either by this.auth itself or by its properties this.auth.token.

    Check whether the properties exist.

    if (this.auth && this.auth.token) {
      req = req.clone({
        setParams: {
          auth: this.auth.token
        }
      })
    }
    

    Or use the operator. ! If you're sure there's a characteristic

    if (this.auth.isAuthenticated()) {
        req = req.clone({
          setParams: {
            auth: this.auth!.token!
          }
        })
     }
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2