【问题标题】:Angular - This condition will always return 'true' since the types 'void' and 'string' have no overlap.ts(2367)Angular - 此条件将始终返回 'true',因为类型 'void' 和 'string' 没有重叠。ts(2367)
【发布时间】:2021-06-02 17:11:25
【问题描述】:

在我的 Angular-11 中,我有以下代码:

user(){
    const data = localStorage.setItem('user', JSON.stringify(this.user));
    if (data != null && data!='undefined') {
      return data;
    }
    this.api.get('auth/user', this.header).subscribe(
      // tslint:disable-next-line:no-shadowed-variable
      data => { this.dataHandler(data) },
      error => { console.log(error) }
    );
  }

但是我收到了这个错误:

此条件将始终返回 'true',因为类型 'void' 和 'string' 没有重叠。ts(2367)

然后突出显示:

if (data != null && data!='undefined') {

我该如何解决?

谢谢

【问题讨论】:

    标签: angular


    【解决方案1】:

    你必须注意到localStorage.setItem()函数没有返回值,const dataundefined赋值。

    【讨论】:

      【解决方案2】:
      const data = localStorage.setItem('user', JSON.stringify(this.user)); // sets data as undefined always
          if (data != null && data!='undefined') { // data !='undefined' => undefined != 'undefined' will always return true
            return data;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-03
        • 2022-11-09
        • 1970-01-01
        • 2020-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-06
        相关资源
        最近更新 更多