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

TypeScript中Promise数组参数类型不兼容报错的解决方法

问题描述

我定义了一个包含Promise<Response>与Promise<void>的数组:

const promises = [
        this.page.waitForResponse(
          (response) =>
            response.url().includes('/my-account/addressform') &&
            response.status() === ResponseCode.SUCCESS
        ),
        this.page.waitForURL(/.*\/delivery-address\/add$/),
      ];

随后定义接收该类型数组的函数:

private async loginAgain(promises: (Promise<Response> | Promise<void>)[]) {...} 

但编译时出现报错:

Argument of type '(Promise<Response> | Promise<void>)[]' is not assignable to parameter of type '(Promise<void> | Promise<Response>)[]'.
  Type 'Promise<Response> | Promise<void>' is not assignable to type 'Promise<void> | Promise<Response>'.
    Type 'Promise<Response>' is not assignable to type 'Promise<void> | Promise<Response>'.
      Type 'Promise<Response>' is not assignable to type 'Promise<void>'.
        Type 'Response' is not assignable to type 'void'.ts(2345)
修复方案

这个报错源于TypeScript对Promise泛型参数的逆变类型检查,Promise<Response>无法兼容Promise<void>,进而导致数组的联合类型校验失败。以下是几种可行的修复方式:

方式一:使用Promise<unknown>[]作为参数类型

Promise<unknown>是所有Promise类型的兼容父类型,能完美接收Promise<Response>和Promise<void>:

private async loginAgain(promises: Promise<unknown>[]) {...} 

方式二:显式声明数组的联合类型

在定义promises数组时,直接指定类型为Promise<Response | void>[],让TypeScript正确识别联合类型:

const promises: Promise<Response | void>[] = [
        this.page.waitForResponse(
          (response) =>
            response.url().includes('/my-account/addressform') &&
            response.status() === ResponseCode.SUCCESS
        ),
        this.page.waitForURL(/.*\/delivery-address\/add$/),
      ];

此时函数参数可以保持(Promise<Response> | Promise<void>)[],或者统一使用Promise<Response | void>[],两种写法都能通过编译。

方式三:使用Promise<any>[](不推荐)

这种方式能快速绕过报错,但会完全丢失类型校验,仅适合临时调试场景:

private async loginAgain(promises: Promise<any>[]) {...} 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:55:19