You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用flashbots simulate返回对象取results时报不存在错误如何解决?

报错原因
  • Flashbots Provider的simulate方法返回值为联合类型:SimulationResponse | RelayResponseError
  • TypeScript做静态类型检查时,无法提前预判运行时返回的是成功的SimulationResponse还是错误的RelayResponseError,而RelayResponseError的类型定义上没有results字段,所以直接访问response.results会触发类型报错。
解决方法

方法1:添加类型守卫判断返回类型(最推荐,符合TS语法规范)

先判断返回值是否为错误响应,排除错误类型后再访问results字段,既解决类型报错也补全了异常处理逻辑:

const response = await flashbotsProvider.simulate(
  simulateTransaction,
  blockNumber + 1
);

// 类型守卫:如果返回值携带error字段则为错误响应
if ("error" in response) {
  // 自定义模拟失败的处理逻辑
  console.error("模拟出错:", response.error);
} else {
  // 此时TS会自动将response类型收窄为SimulationResponse,可正常访问results
  console.log(response.results);
}

方法2:类型断言(仅适合确认模拟一定会成功的测试场景,不推荐生产环境使用)

如果已经通过前置逻辑确认当前调用必然返回成功响应,可以直接对返回值做类型断言跳过检查:

const response = await flashbotsProvider.simulate(
  simulateTransaction,
  blockNumber + 1
) as SimulationResponse;

console.log(response.results);

方法3:可选链运算符(适合临时调试快速规避报错)

用?.访问字段,运行时字段不存在会直接返回undefined不会触发报错,同时也能通过TS类型检查:

console.log(response?.results);

内容的提问来源于stack exchange,提问作者itzmurd4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:24:03