Mahfuz Shuvo
Mahfuz Shuvo

Reputation: 135

error TS2769: No overload matches this call. Type 'string | null' is not assignable to type 'string | string[]'

export class AuthService {

  constructor(private http: HttpClient, private webService: WebRequestService, private router: Router) { }

  login(email: string, password: string) {
    return this.webService.login(email, password).pipe(
      shareReplay(),
      tap((res: HttpResponse<any>) => {
        // auth tokens will be in the header of this response 
        this.setSession(res.body._id, res.headers.get('x-access-token'), res.headers.get('x-refresh-token'));
        console.log('logged in');
      })
    )
  }

  logout() {
    this.removeSession();
    this.router.navigate(['/login']);
  }

  getAccessToken() {
    return localStorage.getItem('x-access-token');
  }

  getRefreshToken() {
    return localStorage.getItem('x-refresh-token');
  }

  getUserId() {
    return localStorage.getItem('user-id');
  }

  setAccessToken(accessToken: any) {
    return localStorage.setItem('x-access-token', accessToken);
  }

  private setSession(userId: string, accessToken: any, refreshToken: any) {
    localStorage.setItem('user-id', userId);
    localStorage.setItem('x-access-token', accessToken);
    localStorage.setItem('x-refresh-token', refreshToken);
  }

  private removeSession() {
    localStorage.removeItem('user-id');
    localStorage.removeItem('x-access-token');
    localStorage.removeItem('x-refresh-token');
  }

  getNewAccessToken() {
    return this.http.get(`${this.webService.ROOT_URL}/users/me/access-token`, {
      headers: {
        'x-refresh-token': this.getRefreshToken(),
        '_id': this.getUserId()
      },
      observe: 'response'
    }).pipe(
      tap((res: HttpResponse<any>) => {
        this.setAccessToken(res.headers.get('x-access-token'));
      })
    )
  }
}

I need a solution to the below error. plz help. Error: src/app/service/auth.service.ts:61:9 - error TS2769: No overload matches this call. The last overload gave the following error. Type 'string | null' is not assignable to type 'string | string[]'. Type 'null' is not assignable to type 'string | string[]'. Type 'string | null' is not assignable to type 'string | string[]'. Type '"response"' is not assignable to type '"body" | undefined'. Error line: 'x-refresh-token': this.getRefreshToken(),

Upvotes: 1

Views: 974

Answers (1)

Ken La
Ken La

Reputation: 170

When reading the doc of storage you can see that Storage.getItem('') return a string or null (see here). With your code I assume that you work on Angular and in the doc, HttpClient headers object can be string | string[] (see here) so there is a conflict with the types.

Maybe you can try something like this to fix the error :

getRefreshToken(): string {
    return localStorage.getItem('x-refresh-token') || '';
 }

Upvotes: 1

Related Questions