对TypeScript使用localStorage.getItem() [英] Use localStorage.getItem() with typescript

查看:20
本文介绍了对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'.

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

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

这会给我一个不同的警告:

Forbidden non-null assertion.

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

推荐答案

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

但是local storage返回类型是string|null,因此它可以同时是stringnull,并且当您声明数据时,它的值为NULL,直到您呈现组件(或调用函数),然后调用getItem函数,它获得值,然后它就是string

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

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

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

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

这篇关于对TypeScript使用localStorage.getItem()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆