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

TS获取图片宽高报错width不存在于GlobalEventHandlers如何解决

报错原因

TypeScript对通用事件回调的this做默认类型推断时,会将onload回调内的this判定为GlobalEventHandlers类型,该类型未定义width、height属性,因此抛出类型错误:

Property 'width' does not exist on type 'GlobalEventHandlers'.

修复方案

任选以下一种方式修改即可:

  • 直接引用已声明的img实例,避开this的类型推断问题,是最稳妥的写法,同时能规避普通函数this指向混乱的隐患:
const img = new Image();
img.onload = function() {
  alert(img.width + 'x' + img.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
  • 给回调内的this做显式类型标注,指定其类型为HTMLImageElement,匹配图片实例的实际类型:
const img = new Image();
img.onload = function(this: HTMLImageElement) {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
  • 使用箭头函数定义回调,箭头函数不绑定自身this,直接引用外部作用域的img实例即可:
const img = new Image();
img.onload = () => {
  alert(img.width + 'x' + img.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

内容的提问来源于stack exchange,提问作者János

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 07:51:24