Type 'string | null' is not assignable to type 'string'.

img

在从localstrage取变量的时候赋值提示此报错 为什么?

TS2322: Type 'string | null' is not assignable to type 'string'.   Type 'null' is not assignable to type 'string'.

localStorage中的authorName键不存在,返回null了,错误提示null无法赋值给string类型变量,做个兼容

this.authorName=localStorage.getItem('authorName')||'';//为null则默认为空字符串

string|null 不能强转成string

TS,getItem获取的东西不一定存在,建议加一层判断,即使你认为一定有,但ts不会从人为角度或全局角度判断

localStorage.getItem('authorName')
key是让你传个值,不是带上key