You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The DOM has a type hierarchy that you can usually ignore while writing JavaScript. But these types become more important in TypeScript. Understanding them will help you write TypeScript for the browser.
Know the differences between Node, Element, HTMLElement, and EventTarget, as well as those between Event and MouseEvent.
Either use a specific enough type for DOM elements and Events in your code or give TypeScript the context to infer it.
Code Samples
functionhandleDrag(eDown: Event){consttargetEl=eDown.currentTarget;targetEl.classList.add('dragging');// ~~~~~ 'targetEl' is possibly 'null'// ~~~~~~~~~ Property 'classList' does not exist on type 'EventTarget'constdragStart=[eDown.clientX,eDown.clientY// ~~~~~~~ ~~~~~~~ Property '...' does not exist on 'Event'];consthandleUp=(eUp: Event)=>{targetEl.classList.remove('dragging');// ~~~~~ 'targetEl' is possibly 'null'// ~~~~~~~~~ Property 'classList' does not exist on type 'EventTarget'targetEl.removeEventListener('mouseup',handleUp);// ~~~~~ 'targetEl' is possibly 'null'constdragEnd=[eUp.clientX,eUp.clientY// ~~~~~~~ ~~~~~~~ Property '...' does not exist on 'Event'];console.log('dx, dy = ',[0,1].map(i=>dragEnd[i]-dragStart[i]));}targetEl.addEventListener('mouseup',handleUp);// ~~~~~ 'targetEl' is possibly 'null'}constsurfaceEl=document.getElementById('surface');surfaceEl.addEventListener('mousedown',handleDrag);// ~~~~~~ 'surfaceEl' is possibly 'null'
functionhandleDrag(eDown: Event){consttargetEl=eDown.currentTarget;targetEl.classList.add('dragging');// ~~~~~ 'targetEl' is possibly 'null'// ~~~~~~~~~ Property 'classList' does not exist on type 'EventTarget'// ...}