reactjstypescriptlocal-storage

Use localStorage.getItem() with typescript


I have the following line of code:

const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal;

Typescript throws this warning:

Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.

So I tried including the non-null assertion operator (!):

const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal;

Which then gives me a different warning:

Forbidden non-null assertion.

I'm new to typescript. What is it looking for here?


Solution

  • Type of JSON.parse dependency must be a string .

    But the local storage return type is string|null so it can be both string and null and when you declare the data, its value is null until you render the component (or call the function) and then call the getItem function, it gets the value, and then it's a string.

    You can use || operator and add a string to it so that it is not null anymore.

    JSON.parse(localStorage.getItem("teeMeasuresAverages") || '""') 
    

    Also you can add // @ts-ignore to prevent TypeScript to check the types in the next line, but it is not recommended

    // @ts-ignore
    JSON.parse(localStorage.getItem("teeMeasuresAverages"))//just the usual way