将 localStorage.getItem() 与打字稿一起使用

Jim*_*ode 30 local-storage typescript reactjs

我有以下代码行:

const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal;
Run Code Online (Sandbox Code Playgroud)

Typescript 抛出此警告:

Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.
Run Code Online (Sandbox Code Playgroud)

所以我尝试包含非空断言运算符(!):

Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.
Run Code Online (Sandbox Code Playgroud)

然后这给了我一个不同的警告:

Forbidden non-null assertion.
Run Code Online (Sandbox Code Playgroud)

我是打字稿新手。它在这里寻找什么?

Yah*_*var 58

依赖类型JSON.parse必须是string.

local storage返回类型是string|null这样的,所以它可以是两者stringnull并且当您声明数据时,其值为空,直到您渲染组件(或调用函数)然后调用getItem,它获取值,然后它是一个string.

您可以使用||运算符并向其中添加一个字符串,使其不再为空。

JSON.parse(localStorage.getItem("teeMeasuresAverages") || '""') 
Run Code Online (Sandbox Code Playgroud)

您还可以添加// @ts-ignore以防止 TypeScript 检查下一行中的类型,但不建议这样做

// @ts-ignore
JSON.parse(localStorage.getItem("teeMeasuresAverages"))//just the usual way 
Run Code Online (Sandbox Code Playgroud)

  • 恐怕这是错误的。`JSON.parse("")` 返回 `JSON 输入意外结束`。因此,如果该项目(尚)不存在,您的代码会破坏整个应用程序。 (7认同)
  • 也尝试一下 `json.parse` `JSON.parse(localStorage.getItem("teeMeasuresAverages")||"")` (2认同)
  • 为了使用 `||`,您应该将其放在表达式 `localStorage.getItem("teeMeasuresAverages") || 之后 ”“` (2认同)

cap*_*ian 12

JSON.parse期望string作为第一个参数

JSON.parse(text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined): any
Run Code Online (Sandbox Code Playgroud)

localStorage返回时string | null

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

Run Code Online (Sandbox Code Playgroud)

如果你想让TS开心就检查一下是否value是一个stirng

const value = localStorage.getItem("teeMeasuresAverages")

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

}

Run Code Online (Sandbox Code Playgroud)

  • 您可以按照您想要的任何方式检查 value 是否为字符串。使用“||”是完全合法的。我只是想解释一下TS抱怨的原因 (3认同)