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

时间:2021-05-26 07:28:16

标签: reactjs typescript local-storage

我有以下代码行:

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'.

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

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

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

Forbidden non-null assertion.

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

2 个答案:

答案 0 :(得分:3)

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

但是 local storage 返回类型是 string|null 所以它可以是 stringnull 并且当你声明数据时,它的值是空的,直到你呈现组件(或调用函数)然后调用 getItem 函数,它获取值,然后它是一个 string

您可以使用 || 操作并为其添加一个字符串,使其不再为空。

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

也可以添加// @ts-ignore来防止type script检查下一行的类型,但不推荐

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

答案 1 :(得分:3)

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

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

}