Tejas Mehta
Tejas Mehta

Reputation: 301

Typescript Error Type 'null' is not assignable to type

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

}

Upvotes: 6

Views: 41546

Answers (4)

Tanuwo
Tanuwo

Reputation: 129

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 = {}
}

Upvotes: 2

Ehrlich_Bachman
Ehrlich_Bachman

Reputation: 932

I run into the same error and just fixed it by:

const currentName =  String(localStorage.getItem('FileName') || '');

Upvotes: 0

user24950814234
user24950814234

Reputation: 2037

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;
}

Upvotes: 8

fortunee
fortunee

Reputation: 4332

You need to parse it back to an object with JSON.parse

this.currentName =  JSON.parse(localStorage.getItem('FileName'));

Upvotes: 0

Related Questions