JimmyTheCode
JimmyTheCode

Reputation: 5694

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?

Upvotes: 34

Views: 72807

Answers (5)

Yaya
Yaya

Reputation: 4838

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 

Upvotes: 62

Sebastian Vorac
Sebastian Vorac

Reputation: 4663

In general:

  const item = localStorage.getItem(itemName)
  const result = item ? JSON.parse(item) : undefined

Function for getting item from localStorage in Next.js can look like this:

const ISSERVER = typeof window === 'undefined'
export const getItemFromLocalStorage = (itemName: string) => {
  if (ISSERVER) return
  const item = localStorage.getItem(itemName)
  return item ? JSON.parse(item) : undefined
}

and we can move the ISSERVER to constants/window.ts

Upvotes: 1

Newbie21
Newbie21

Reputation: 163

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")

Upvotes: 3

Emilio
Emilio

Reputation: 1

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

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

Upvotes: -3

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

}

Upvotes: 12

Related Questions