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

TypeScript中‘string | Event无法赋值给ErrorEvent’报错的原因与修复

报错原因

TypeScript对HTMLImageElement.onerror的类型定义是:该回调函数的参数可以是Event对象,也可以是字符串(这是为了兼容早期浏览器的行为,部分旧浏览器会直接传入错误信息字符串而非事件对象)。你强制把参数类型指定为ErrorEvent,就会和TS的类型定义冲突,触发类型不兼容的报错。

修复方法
  • 使用联合类型兼容两种情况
    把回调参数的类型改成ErrorEvent | string,覆盖所有可能的输入:

    const image = new Image() as HTMLImageElement;
    image.src = src;
    image.onload = function() {...};
    image.onerror = function(evt: ErrorEvent | string) {
      if (typeof evt === 'string') {
        // 处理字符串类型的错误信息
        console.error('加载错误:', evt);
      } else {
        // 处理ErrorEvent对象
        console.error('加载错误:', evt.message);
      }
    };
    
  • 使用类型断言(仅当你确定环境不会传字符串时)
    如果你明确代码运行的现代浏览器只会传入ErrorEvent,可以用类型断言跳过TS的类型检查:

    const image = new Image() as HTMLImageElement;
    image.src = src;
    image.onload = function() {...};
    image.onerror = function(evt: unknown) {
      const errorEvt = evt as ErrorEvent;
      console.error('加载错误:', errorEvt.message);
    };
    
  • 利用TypeScript的DOM类型细化
    现代浏览器中onerror的参数是Event的子类ErrorEvent,你可以通过类型守卫细化类型:

    const image = new Image() as HTMLImageElement;
    image.src = src;
    image.onload = function() {...};
    image.onerror = function(evt: Event) {
      if (evt instanceof ErrorEvent) {
        console.error('加载错误:', evt.message);
      }
    };
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 19:55:55