Typescript Error Type 'null' is not assignable to type

17,688

Solution 1

fortunee is correct, however since everything in localStorage is stored as strings, Typescript has no way of guaranteeing that the object is still the same object. In this case, you need to tell Typescript what type the parsed object will be with a cast.

this.currentName =  JSON.parse(localStorage.getItem('FileName') || '{}') as FileName;

Afterwards you may want to duck type to make sure that this.currentName isn't an empty object (this could've happened if the user cleared their localStorage).

Example:

if (this.currentName.fname == null) {
  // Give the user an error message or something...
  this.currentName = undefined;
}

Solution 2

in case there's an error when parsing an object you can use try-catch to set the default value for it

try {
  this.currentName =  JSON.parse(localStorage.getItem('FileName')) as FileName;
} catch(e){
  this.currentName = {}
}
Share:
17,688
Tejas Mehta
Author by

Tejas Mehta

Updated on June 26, 2022

Comments

  • Tejas Mehta
    Tejas Mehta almost 2 years

    In my project I am using Angular LocalStorage to store value of the record which is of Type Filename. I am getting below error in back method

    Error

    Type 'string | null' is not assignable to type 'FileName | undefined'.
      Type 'null' is not assignable to type 'FileName | undefined'.
    

    I need help to solve this error, below is my code

    Code

    
    export interface FileName {
        fname: number;
        sname: number;
        Tange: number;
        quick: string;
        Mark: string;
        mine: number;
    }
    
    currentName: FileName | undefined = undefined;
    previousName: FileName | undefined = undefined;
    
    data(rec: FileName, Mark: HTMLTableDataCellElement) {
      const { fname, sname, Tange, record_id, mine } = rec;
      const quick = Mark.innerText;
      this.name.replaceAndNew({sname, Tange, record_id, quick, mine, fname}).subscribe(data => {
        this.process(data);
      })
       localStorage.setItem('FileName', JSON.stringify(rec));
    }
    
    back(){
      localStorage.getItem('FileName');
      this.currentName =  localStorage.getItem('FileName'); -----------------> Error
    
    }