【问题标题】:Getting an error Argument of type 'unknown' is not assignable to parameter of type 'Error | null'获取错误“未知”类型的参数不能分配给“错误”类型的参数 |空值'
【发布时间】:2021-11-17 20:46:25
【问题描述】:

我对打字稿相当陌生,所以我收到一个错误,说“未知”类型的参数不能分配给“错误”类型的参数 | null',我不明白为什么会这样。我该如何解决?

export function subscribeToAccount(
  web3: Web3,
  callback: (error: Error | null, account: string | null) => any
) {
  const id = setInterval(async () => {
    try {
      const accounts = await web3.eth.getAccounts();
      callback(null, accounts[0]);
    } catch (error) {
      callback(error, null);
    }
  }, 1000);

  return () => {
    clearInterval(id);
  };
}

【问题讨论】:

    标签: reactjs typescript web3 web3js


    【解决方案1】:

    错误是由这一行引起的:

    callback(error, null);
    

    catch (error) 中的error 的类型是unknown,并且您指定callback 函数接受Error | null 作为其第一个参数,这就是错误的原因。

    阅读更多here


    简单,但不推荐修复

    在您的 tsconfig 文件上将 strict 值设置为 false


    另一种简单但更好的方法

    error 类型显式指定为any

    try {
      const accounts = await web3.eth.getAccounts();
      callback(null, accounts[0]);
    } catch (error: any) {
      callback(error, null);
    }
    

    最好的方法

    在 catch 中进行类型检查

    try {
      const accounts = await web3.eth.getAccounts();
      callback(null, accounts[0]);
    } catch (error) {
      if (error instanceof Error ) {
        callback(error, null);
      } else {
        // handle
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2021-10-03
      • 1970-01-01
      • 2019-10-22
      • 2022-11-12
      • 2020-01-05
      • 2020-06-21
      • 1970-01-01
      相关资源
      最近更新 更多