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

Use localStorage.getItem() with typescript

我有下面一行代码:

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.

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

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

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

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

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

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

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

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

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

localStoragereturnsstring | null.

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

如果你想让 TS 高兴,只需检查 value 是否是 stirng

const value = localStorage.getItem("teeMeasuresAverages")

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

}

我发现这似乎对我使用打字稿有帮助:

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

因此,对于给定的解决方案,存在无法解析空字符串的错误。 它会给你一个 Uncaught SyntaxError: Unexpected end of JSON input for JSON.parse("") 的错误。更多详情 .

所以我的解决方案是使用 || 部分给出一个默认值,如果您在本地存储中找不到您正在寻找的变量,您将希望发生什么。例如

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