Use localStorage.getItem() with typescript

Viewed 20283

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?

4 Answers

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 

JSON.parse expects string as a first argument

JSON.parse(text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined): any

When localStorage returns string | null.

const value = localStorage.getItem("teeMeasuresAverages") // string | null

If you want to make TS happy just check if value is a stirng

const value = localStorage.getItem("teeMeasuresAverages")

if (typeof value === 'string') {
    const parse = JSON.parse(value) // ok

}

So with the given solutions there is an error you can't parse an empty string. It will give you an error of Uncaught SyntaxError: Unexpected end of JSON input for JSON.parse(""). More details here.

So my solution would be use || part to give a default value of what you will want to happen if you can't find the variable you were looking for in the local storage. For e.g.

JSON.parse(localStorage.getItem("isItTrueOrFalse") || "false")

I found out that this seems to help me while using typescript:

JSON.parse(`${localStorage.getItem('localStorage-value')}`);
Related