Issue TS2769: No matching overload found for this call. The type 'string | null' cannot be assigned 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(), // This line is causing an error
        '_id': this.getUserId()
      },
      observe: 'response'
    }).pipe(
      tap((res: HttpResponse<any>) => {
        this.setAccessToken(res.headers.get('x-access-token'));
      })
    )
  }
}

I'm looking for a solution to resolve the following error. Please assist. 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(),

Answer №1

Upon reviewing the documentation for storage, it is clear that Storage.getItem('') will either return a string or null (see here). Based on your code snippet, it appears that you are working with Angular and according to the documentation, the HttpClient headers object can be of type string | string[] (see here), creating a conflict in types.

To resolve this issue, you may want to consider implementing something like the following:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript navigation and Next.js technology

Currently, I am in the process of learning typescript and attempting to create a navigation bar. However, I encountered an error message stating "Unexpected token header. Expected jsx identifier". I am a bit puzzled by this issue. Could someone kindly pro ...

Encountering a compilation error due to a Typescript assignment

While working with Typescript, I encountered a compilation error in the code shown below: console.log('YHISTORY:login: data = '+data); let theData = JSON.parse(data); console.log('YHISTORY:login: theData = '+JSON.stringify(theData)); ...

Is it possible to import in TypeScript using only the declaration statement?

Is there a way to use a node module in TypeScript without explicitly importing it after compilation? For example: I have a global variable declared in a file named intellisense.ts where I have: import * as fs from 'fs'; Then in another file, ...

Error encountered when providing valid data types as arguments in a React/Typescript function

I am facing an issue when passing a string variable to a function. To address this, I have created an interface called MyMessageProps where I declare the message as a string. Subsequently, the function MyMessage utilizes this interface to return with the ...

Utilizing data from the home component in another component: A guide

Here is the code I am working with, showcasing how to utilize (this.categoryType) in another component: getCategoryDetails(){ return this.http.get('ip/ramu/api/api/…') .map((res:Response) => res.json()); } The above code snippet is utilize ...

Modifying state within reducers is not allowed

Encountered the following error while using @ngrx/store: index.js?4b23:19 State mutation is prohibited inside of reducers. (anonymous) @ index.js?4b23:19 (anonymous) @ index.ts:54 rootReducer @ index.ts:70 _initialStateFactory @ ng2.ts?2a33:24 AppModule ...

What could be causing my "Swiper" component to malfunction in a TypeScript React project?

In my React project, I decided to incorporate the Swiper library. With multiple movie elements that I want to swipe through, I began by importing it as follows: import Swiper from 'react-id-swiper'; Utilizing it in my code like this: <div cla ...

Creating a TypeScript generic type for the "pick" function to define the types of values in the resulting object

I am facing an issue while writing the type for the pick function. Everything works smoothly when picking only one key or multiple keys with values of the same type. However, if I attempt to pick a few keys and their values are of different types, I encoun ...

Utilizing AngularJS2 with PHP on Apache server

Starting my journey with AngularJS today. Following tutorials on AngularJS version 2 using JavaScript. Node.js is a requirement, but my current development environment includes PHP, MySQL, and Apache (Xampp). I am curious if it is possible to develop and ...

Exploring how to utilize class properties within Angular templates

I am facing an issue with using a template property in Angular. Despite my attempts, it is not functioning as expected and I am unable to pinpoint the cause of the problem. To illustrate, I have set up a demonstration here: https://github.com/Fulkerson/an ...

The use of data binding can lead to the error known as ExpressionChangedAfterItHasBeen

Just getting started with Angular 4 and encountering an ExpressionChangedAfterItHasBeenCheckedError in my data binding field. Here's the code snippet: <form> <div> <h2>Hello {{input.value}}</h2> <input type="text" [valu ...

What is the best method for setting up a worldwide list of approved URLs?

Looking to incorporate a universal whitelist feature for secure URLs in bypassing resource URLs within Angular 2, inspired by the functionality offered in AngularJS via the $sceDelegateProvider as explained here I've attempted to consult the Angular ...

Tips for using CanActivate in Angular 5 with angular2-jwt

I am in the process of incorporating the canActivate class to manage URL access. To handle token loading, I have created the following functions: saveToken(jwt:string){ this.jwtToken = jwt; localStorage.setItem('token',jwt); let jwtH ...

Unable to allocate FormArray

Just delved into learning Angular and encountered a snag. I am trying to add and remove textfields for a form, so I attempted the following code in my component.ts file: import {FormBuilder, FormGroup, FormArray } from '@angular/forms'; This is ...

Navigating in Angular with parameters without modifying the URL address

In a nutshell, my goal is to navigate to a page with parameters without showing them in the URL. I have two components: Component A and B. What I want to do is route to B while still needing some parameters from A. I know I can achieve this by setting a ...

Steps for dynamically adding a link to images in React with TypeScript based on a condition

In my project, I am looking to dynamically add links to images based on certain conditions using JavaScript and React. Here's what I aim to achieve: I have separate mobile and desktop images in my application. Under the mobile image, there is a text ...

The presence of an Angular Element within an Angular application can lead to a problematic cycle of constant reloading,

, I am encountering issues with integrating Angular Elements as plugins into my Angular application. The problem arises when building the element with "--prod" - it functions properly with "ng serve" in my development setup but causes infinite reloading wh ...

Encountering the identical error message while attempting to execute my application: "Uncaught TypeError: this.microservicesModule.register is not a function."

Despite my repeated attempts to run the application, I am consistently encountering the following error message: "UnhandledPromiseRejectionWarning: TypeError: this.microservicesModule.register is not a function at NestApplication.registerModules ...

What is the process for exporting all sub-module types into a custom namespace?

When we import all types from a module using a custom-namespace, it appears to work smoothly, for example: import * as MyCustomNamespace from './my-sub-module' We are also able to export all types from a module without creating a new namespace, ...

When using Angular server-side pagination with ngrx and Express in Node.js, I often encounter discrepancies in the indexing across different stacks

After successfully implementing server-side pagination in Angular, I encountered an issue where the page was set to 1 initially, but the mat-paginator component started at index 2. Despite functioning correctly when changing pages, this discrepancy puzzled ...