-1

The following code gives the Object is possibly null error in line +localStorage.getItem('PID'):

newPropID() {
  if (localStorage.getItem('PID')) {
    localStorage.setItem('PID', String(+localStorage.getItem('PID') + 1));
    return +localStorage.getItem('PID');
  } else {
    localStorage.setItem('PID', '101');
    return 101;
  }
}

I want to check if there's a record in local storage and store another record. How can I fix this?

vindi96
  • 113
  • 2
  • 10
  • Does this answer your question? [How to check whether a Storage item is set?](https://stackoverflow.com/questions/3262605/how-to-check-whether-a-storage-item-is-set) – kogonidze May 19 '21 at 07:14
  • 1
    you should refactor - get the PID. check that is null set it to 101 else increment and return the increment. You duplicate code to increment as is. Also you assign 101 twice - what if you want a different seed (101 atm). 2 places to update. Maintainability... – JGFMK May 19 '21 at 07:16

1 Answers1

0

Typescript can infer the possible value if you abstract it to a variable:

newPropID() {
  const PID = localStorage.getItem('PID');
  if (PID) {
    const updatedPID = String(+PID + 1);

    localStorage.setItem('PID', updatedPID);
    return updatedPID;
  } else {
    localStorage.setItem('PID', '101');
    return 101;
  }
}
MaartenDev
  • 5,631
  • 5
  • 21
  • 33