这边TS报错怎么修改呢?
因为 localStorage.getItem('userInfo')
可能会是 null
,JSON.parse
接收的是参数类型是 string
,null
不能赋值给 string
所以应该这样写:
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '')
如果确定 localStorage.getItem('userInfo')
有值可以使用 !
非空断言
const userInfo = JSON.parse(localStorage.getItem('userInfo')!)
10 回答11.7k 阅读
2 回答3.2k 阅读✓ 已解决
2 回答4.3k 阅读✓ 已解决
3 回答1.9k 阅读✓ 已解决
2 回答1.7k 阅读✓ 已解决
4 回答2.5k 阅读✓ 已解决
5 回答3.8k 阅读
const a = JSON.parse(localStorage.getItem('df') as string)
const a = JSON.parse(localStorage.getItem('df') || '')