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
相关产品推荐
相关产品推荐

