【问题标题】:Use localStorage.getItem() with typescript将 localStorage.getItem() 与打字稿一起使用
【发布时间】:2021-08-14 10:18:35
【问题描述】:

我有以下代码行:

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.

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

【问题讨论】:

    标签: reactjs typescript local-storage


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      但是local storage返回类型是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 
      

      【讨论】:

      • 谢谢,但我仍然收到Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.
      • 试试json.parseJSON.parse(localStorage.getItem("teeMeasuresAverages")||"")
      • 为了使用||,你应该把它放在表达式localStorage.getItem("teeMeasuresAverages") || ""之后
      【解决方案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
      
      }
      
      

      【讨论】:

      • 谢谢!对于一个简单的 localStorage 请求来说,这似乎非常冗长,但它仍然是我遇到的最好的解决方案。
      • 你可以用任何你想要的方式检查 value 是否是一个字符串。使用|| 是完全合法的。我只是想解释一下为什么 TS 抱怨
      猜你喜欢
      • 1970-01-01
      • 2017-07-31
      • 2017-08-15
      • 2017-12-25
      • 2021-02-13
      • 2019-10-06
      • 2019-04-18
      • 2021-08-21
      • 1970-01-01
      相关资源
      最近更新 更多