【发布时间】:2021-09-30 20:18:19
【问题描述】:
JSON.parse(sessionStorage.getItem('owner'))
==>
'string | 类型的参数null' 不能分配给“字符串”类型的参数。
类型 'null' 不能分配给类型 'string'。
并且返回 null;
==>
类型 'null' 不能分配给类型 'string'。
public get owner(): Owner{
if(this._owner != null){
return this._owner;
} else if (this._owner == null && sessionStorage.getItem('owner') != null){
this._owner = JSON.parse(sessionStorage.getItem('owner')) as Owner; // <== HERE
return this._owner;
}
return new Owner();
}
public get token(): string{
if (this._token != null) {
return this._token;
} else if (this._token == null && sessionStorage.getItem('token') != null) {
this._token = sessionStorage.getItem('token') as string;
return this._token;
}
return null; // <== HERE: Type 'null' is not assignable to type 'string'.
}
【问题讨论】:
-
null确实不能分配给类型string。如果您希望您的函数能够返回字符串或 null,请将其返回类型设置为string | null
标签: angular typescript angular12 typescript4.0