programing

typescript와 함께 localStorage.getItem() 사용

starjava 2023. 7. 1. 07:56
반응형

typescript와 함께 localStorage.getItem() 사용

코드 라인은 다음과 같습니다.

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

Typescript에서 다음 경고가 발생합니다.

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

그래서 null이 아닌 어설션 연산자(!)를 포함하려고 했습니다.

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

그러면 다른 경고가 나옵니다.

Forbidden non-null assertion.

타자는 처음입니다.여기서 뭘 찾는 거지?

유형:JSON.parse종속성은 다음과 같아야 합니다.string.

그런데 그.local storage반환 유형은 다음과 같습니다.string|null둘 다가 될 수 있습니다.string그리고.null그리고 당신이 데이터를 선언할 때, 그것의 값은 당신이 구성 요소를 렌더링(또는 함수를 호출)한 다음에 호출할 때까지 null입니다.getItem함수, 그것은 가치를 얻고, 그리고 나서 그것은.string.

사용할 수 있습니다.||연산자를 사용하여 더 이상 null이 되지 않도록 문자열을 추가합니다.

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

또한 추가할 수 있습니다.// @ts-ignoreTypeScript가 다음 줄에 있는 유형을 확인하지 못하도록 하지만 권장되지는 않습니다.

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

JSON.parse을 기대합니다.string제1의 논거로서

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

언제localStorage돌아온다string | null.

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

만약 당신이 TS를 행복하게 하고 싶다면, 그냥 확인하세요.value스팅입니다

const value = localStorage.getItem("teeMeasuresAverages")

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

}

따라서 지정된 솔루션에서는 빈 문자열을 구문 분석할 수 없는 오류가 발생합니다.그것은 당신에게 오류를 줄 것입니다.Uncaught SyntaxError: Unexpected end of JSON input위해서JSON.parse("")자세한 내용은 여기에 있습니다.

그래서 제 해결책은||로컬 스토리지에서 찾고 있던 변수를 찾을 수 없는 경우 발생할 작업에 대한 기본값을 제공합니다.예를 들어.

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

일반적으로:

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

Next.js의 localStorage에서 항목을 가져오는 기능은 다음과 같습니다.

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

그리고 우리는 움직일 수 있습니다.ISSERVER로.constants/window.ts

타이프스크립트를 사용하는 동안 이 방법이 도움이 된다는 것을 알게 되었습니다.

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

언급URL : https://stackoverflow.com/questions/67700374/use-localstorage-getitem-with-typescript

반응형