【问题标题】:TypeScript Type 'string | null' is not assignable to type 'string'打字稿类型'字符串| null' 不可分配给类型 'string'
【发布时间】:2022-01-17 02:04:21
【问题描述】:

在这个片段中我有下一个错误:

Type 'string | null' is not assignable to type 'string'.
  Type 'null' is not assignable to type 'string'.  TS2322
export async function GetCertainCoinByType(coinId: string) {
  const response = await axios.get(URLofCertainCoins + `certain/${coinId}`, {
      headers : {
          token : localStorage.getItem('token'),
      }
  });
  return response;
}

【问题讨论】:

  • Localestorage getItem 可能会返回 null,因此您需要检查这一点。我个人会抛出异常,因为在没有令牌的情况下调用此 fn 似乎无效。

标签: javascript node.js typescript


【解决方案1】:

首先检查token是否为null,如果是则退出函数。

现在response 无论如何都是一个Promise,因为它是由async 函数返回的。你不需要await Axios,然后再将其重新转换为 Promise。你可以直接return axios.get(...),因为这会删除唯一的await,所以你甚至不需要async/await语法。

export function GetCertainCoinByType(coinId: string): Promise<any> {

  const token:string|null = localStorage.getItem('token');

  if(!token){
    console.log("No token!");
    return ;
  }

  return axios.get(URLofCertainCoins + `certain/${coinId}`, {
      headers : { token }
  });
}

【讨论】:

  • 真的没有理由放token:string|null,隐式类型在这里很好。边界检查很重要..
  • 我的目标是为了演示和明确的答案而明确:)
  • 好吧,这很有道理..只是想确保其他人阅读这篇文章不要认为这里是明确的解决问题的方法,而不是边界检查..
【解决方案2】:

这是因为Local storage 的返回类型是string | null,而不仅仅是string。为避免此异常,您可以先从本地存储中获取项目,然后像这样使用它:

export async function GetCertainCoinByType(coinId: string) {
  let tokenFromStorage = localStorage.getItem('token')
  if (!tokenFromStorage ) { 
    throw new Error("no token supplied"); 
  }
  const response = await axios.get(URLofCertainCoins + `certain/${coinId}`, 
  {
      headers : {
          token : tokenFromStorage 
      }
  });
  return response;
}

【讨论】:

  • 快到了,你忘了输入边界检查。例如。在let 之后的下一行,只需输入类似 -> if (tokenFromStorage === null) { throw new Error("no token supplied"); } 或类似的内容。这会让 TS 开心。
  • 我试图指出避免错误的使用,因为在 OP 的角度会存在令牌。但这不是真的,同意。更新了答案。感谢您指出@CollinD 和 Keith
  • 不幸的是,您调用getItem 的更新将再次导致错误.. :( 使用您原来的let,并在let 之后进行检查将解决该问题。因为getItem 将始终返回string | null ,但在对let 进行边界检查后,它将变为string..
  • 不知道为什么我很着急,只是这样做
猜你喜欢
  • 2021-09-21
  • 2019-04-10
  • 2016-10-25
  • 2019-07-09
  • 1970-01-01
  • 2021-06-12
  • 2022-08-14
  • 2020-02-07
  • 2018-02-02
相关资源
最近更新 更多