TypeScript为eventListener及回调添加强类型解决类型报错问题
问题解决方案
需要修改三个地方的类型定义即可消除全部报错:
- 给构造函数入参
onMouseDown明确类型,解决@typescript-eslint/no-unsafe-call报错:原代码中onMouseDown未指定类型默认是any,明确为(event: MouseEvent | TouchEvent, handle: ResizeHandle) => void即可通过校验。 - 调整
_handle的类型定义:原Element类型的事件映射表不包含mousedown、touchstart这类交互事件,改为HTMLDivElement | null即可匹配事件类型校验,不需要保留undefined类型,构造函数执行完成后_handle要么是生成的div元素要么是null。 - 调整
_onResize的校验逻辑:调用removeEventListener前先判断_onResize是否存在,避免把null/undefined传入事件监听移除方法,消除类型不匹配报错。
修改后的完整代码如下:
import { Renderer2 } from '@angular/core'; export class ResizeHandle { protected _handle: HTMLDivElement | null = null; private _onResize: ((event: MouseEvent | TouchEvent) => void) | null = null; constructor( protected parent: Element, protected renderer: Renderer2, public type: string, public css: string, // 明确onMouseDown的类型 private onMouseDown: (event: MouseEvent | TouchEvent, handle: ResizeHandle) => void ) { // generate handle div const handle = renderer.createElement('div') as HTMLDivElement; renderer.addClass(handle, 'resizable-handle'); renderer.addClass(handle, css); // add default diagonal for se handle if (type === 'se') { renderer.addClass(handle, 'resizable-diagonal'); } // append div to parent if (this.parent) { parent.appendChild(handle); } // create and register event listener this._onResize = (event: MouseEvent | TouchEvent) => { onMouseDown(event, this); }; handle.addEventListener('mousedown', this._onResize, { passive: false }); handle.addEventListener('touchstart', this._onResize, { passive: false }); this._handle = handle; } dispose(): void { // 提前判断_onResize存在,避免传入空值 if (this._handle && this._onResize) { this._handle.removeEventListener('mousedown', this._onResize); this._handle.removeEventListener('touchstart', this._onResize); if (this.parent) { this.parent.removeChild(this._handle); } } this._handle = null; this._onResize = null; } get element(): HTMLDivElement | null { return this._handle; } }
内容的提问来源于stack exchange,提问作者methuselah
相关产品推荐
相关产品推荐

