【问题标题】:Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'. Angular 12'string | 类型的参数null' 不能分配给“字符串”类型的参数。类型“null”不能分配给类型“string”。角 12
【发布时间】: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'.

}

【问题讨论】:

标签: angular typescript angular12 typescript4.0


【解决方案1】:

您将token() 定义为仅返回string,但您试图返回null。您可以更改定义以返回string | null

public get token(): string | null {
    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;
}

当然,使用这个 getter 的代码需要考虑到这一点。

【讨论】:

    猜你喜欢
    • 2018-04-05
    • 1970-01-01
    • 2021-09-06
    • 2021-09-22
    • 2021-06-12
    • 1970-01-01
    • 2022-01-27
    • 2021-07-14
    • 2021-10-02
    相关资源
    最近更新 更多