这边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')!)
13 回答12.8k 阅读
8 回答2.6k 阅读
2 回答5.1k 阅读✓ 已解决
7 回答2k 阅读
3 回答2.2k 阅读✓ 已解决
5 回答903 阅读
3 回答1.1k 阅读✓ 已解决
const a = JSON.parse(localStorage.getItem('df') as string)
const a = JSON.parse(localStorage.getItem('df') || '')