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

Creating TypeScript Unions dependent on a nested object's property

I want to create a Union Type that is dependent on a nested property within my object. Take a look at the example provided below: type Foo = { abilities: { canManage: boolean } } type Bar = { abilities: { canManage: boolean ...

Running an Angular 4 application on a centOS server

I am looking to deploy my Angular 4 Application on my CentOS Server for the first time. Following recommendations from various threads, I have already installed Apache on it. I understand that I need to run ng build --prod to generate a dist file that ca ...

Steps to access a Request object within a Controller

I am currently working with Express and Typescript, utilizing Controllers for managing requests. In an attempt to create a BaseController that includes the Request and Response objects for each request, I wrote the following code snippet. However, it see ...

ReferenceError: 'exports' is undefined in the context of Typescript Jest

I'm currently delving into unit testing with jest and encountered an error that looks like this: > npm run unit > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771f181012374659475947">[email protected]</ ...

What is the process for connecting a global variable to a BehaviorSubject?

I'm currently working on implementing a login feature in my application, and I want specific buttons within the app.component template to only be visible once the user successfully logs in. To achieve this, I am attempting to utilize BehaviorSubject. ...

What is the correct method for updating RxJS to the most recent version?

While attempting to update to the most recent version of RxJS, I followed the instructions from this documentation: https://github.com/reactivex/rxjs However, I encountered these warnings: npm warn @angular/[email protected] requires a peer of rxjs@ ...

Retrieving the main color specified in the custom theme within the component's SCSS file

After creating a custom theme in Angular 4, I am trying to use it in one of my component's SCSS file. Specifically, I want the background of a particular mat-grid-tile to reflect the primary color of the theme. Here is my custom theme: @import &apo ...

"Overcoming obstacles in managing the global state of a TypeScript preact app with React/Next signals

Hello, I recently attempted to implement a global app state in Preact following the instructions provided in this documentation. However, I kept encountering errors as this is my first time using useContext and I suspect that my configuration might be inco ...

Alter the style type of a Next.js element dynamically

I am currently working on dynamically changing the color of an element based on the result of a function //Sample function if ("123".includes("5")) { color = "boldOrange" } else { let color = "boldGreen" } Within my CSS, I have two clas ...

Pass data between different parts of the system

Utilizing the angular material paginator has been a great experience for me. You can check it out here: https://material.angular.io/components/paginator/examples. The paginator triggers an event which allows me to print the page size and page index. This f ...

The React-Typescript error message is stating that the module "react-router-dom" does not have the exported member "RouteComponentProps"

I encountered an issue with my project involving a login page and the usage of "RouteComponentProps". Unfortunately, I received the following error: Module '"react-router-dom"' has no exported member 'RouteComponentProps'. Upon attempt ...

Angular2 routing does not trigger the Component constructor and Router life-cycle hooks when the router.parent.navigate method is called from a child component

I am currently working on an application that includes child routes. The parent component (App component) consists of 2 routes: @RouteConfig([ { path: '/overview', name: 'Overview', component: OverviewComponent, useAsDefault:true }, { ...

In Angular 12, the button click should only proceed once a method with an HTTP call has finished executing

Users can input multiple search criteria into the form and initiate a search operation by clicking the search button. Some of the fields in the search criteria form are dropdowns. Choosing a value from a dropdown triggers an API call to retrieve a specifi ...

Typescript's definition file includes imports that can result in errors

Occasionally, typescript may generate a definition file with code like the following, leading to compile errors: // issue.ts import { Observable } from 'rxjs'; class Issue { get data() { return new Observable(); } } // issue.d.ts class ...

Tips for assigning types from an interface object in TypeScript

Here is the code snippet I'm dealing with interface deviceInfo { Data: { model: string; year: number; }; } const gadget: deviceInfo.Data; I encountered a warning in vscode that indicates there ...

Bringing in Data with Angular

For my Angular projects, I attempted to utilize csv files in the following manner: import * as data1 from "./data.csv"; import * as data2 from "./data2.csv"; These files are situated in the same directory as the .ts file that I am trying to access them w ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

The integration of Angular 6 with AngularJS components fails to load properly in a hybrid application

Currently, I am in the process of upgrading a large AngularJS version 1.7.3 to a hybrid app using Angular 6. The initial phase involved converting all controllers/directives into an AngularJS component. Subsequently, I created a new Angular 6 project skele ...

RC7 is missing the necessary HTTP_PROVIDERS for the resolveAndCreate HTTP method in Angular2

During the time of RC4, I was able to create my own custom http instance using a function like this: export function createHTTP(url:string, headers?:Headers){ let injector = ReflectiveInjector.resolveAndCreate([ myHttp, {provide:'defaultUrl ...

Navigating Unknown Properties in Angular: A Guide to Iterating Through Arrays

I'm having trouble coming up with a title for my question. I want to loop through an array of dynamic objects coming from a database, but I don't know the properties of the objects. Here's an example of the array object: [{ "id": 9, ...