代码之家  ›  专栏  ›  技术社区  ›  Sai Krishnadas

无法将任何类型分配给localStorage

  •  0
  • Sai Krishnadas  · 技术社区  · 5 年前
    const getAccessToken = () => {
        if (localStorage.getItem('tokens')) {
          const token = JSON.parse(localStorage.getItem('tokens'))['accessToken'];
          return token
        } else {
          return null;
        }
      }
    

    错误:

    Argument of type 'string | null' is not assignable to parameter of type 'string'.
      Type 'null' is not assignable to type 'string'.
    

    我尝试声明type:any,但问题仍然没有解决

    2 回复  |  直到 5 年前
        1
  •  4
  •   akuiper    5 年前

    尝试移动表达式 localStorage.getItem('tokens')

    const getAccessToken = () => {
      let tokens = localStorage.getItem('tokens')
      if (tokens) {
        const token = JSON.parse(tokens)['accessToken'];
        return token
      } else {
        return null;
      }
    }
    

    Playground

    这里的问题是,当您使用表达式时,编译器无法将其与 if string . 相反,它仍然被考虑 string | null .

        2
  •  0
  •   smac89    5 年前

    你只需要 !

    const getAccessToken = () => {
      if (localStorage.getItem('tokens')) {
        const token = JSON.parse(localStorage.getItem('tokens')!)['accessToken'];
        return token
      } else {
        return null;
      }
    }
    

    有时编译器需要 告诉 提醒 怎么办

    推荐文章