typescriptangular11angular-local-storage

argument of type string | null is not assignable to parameter of type string error


When I try to get local storage records It gives following error.

"Argument of type 'string | null' is not assignable to parameter of type 'string'.\n  Type 'null' is not assignable to type 'string'.",

here is the code

this.service.getAllPets(this.CatDog).subscribe(
  data => {
    this.pets = data;
    console.log(data);
    // tslint:disable-next-line:no-bitwise
    const newPet = JSON.parse(localStorage.getItem('newPet'));
    if (newPet){
      this.pets = [newPet, ...this.pets];
    }
    console.log(this.route.snapshot.url.toString());
  }, error => {
    console.log('httperror:');
    console.log(error);
  }
);

Solution

  • JSON.parse accepts an arg of type string

    localStorage.getItem returns an arg of type string or null (if its not found)

    therefore you can add a quick default value set before the parse. like so:

    const newPet = JSON.parse(localStorage.getItem('newPet') || "{}");
    

    another option is to fetch the result from the localstorage, check that it is not null and then parse it.