Currently in the process of transitioning my old JavaScript code to TypeScript. One of the components I have is a Table Of Contents JSX component that helps me navigate easily to specific headings.
I had a function that calculated the total offset needed for scrolling to a particular heading. However, after converting it to a '.tsx' file, an error popped up:
The error reads: 'Type 'Element' is missing the following properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and 107 more.'
// TOC.tsx
...
const accumulateOffsetTop = ( el: HTMLElement | null, totalOffset = 0 ) => {
while ( el ) {
totalOffset += el.offsetTop - el.scrollTop + el.clientTop
el = el.offsetParent // <- Error occurs here
}
return totalOffset
}
...
This function gets called at this location:
// TOC.tsx
...
export default function Toc(
{ headingSelector, getTitle, getDepth, ...rest }
) {
const { throttleTime = 200, tocTitle = `Contents` } = rest
const [headings, setHeadings] = useState( {
titles: [],
nodes: [],
minDepth: 0,
offsets: [],
} )
const [open, setOpen] = useState( false )
const [active, setActive] = useState()
const ref = useRef()
useOnClickOutside( ref, () => setOpen( false ) )
useEffect( () => {
const selector = headingSelector || Array.from(
{ length: 6 }, ( _, i ) => `main > h` + ( i + 1 )
)
const nodes = Array.from( document.querySelectorAll( selector ) )
const titles = nodes.map( node => ( {
title: getTitle ? getTitle( node ) : node.innerText,
depth: getDepth ? getDepth( node ) : Number( node.nodeName[1] ),
} ) )
const minDepth = Math.min( ...titles.map( h => h.depth ) )
const startingOffsets = nodes.map( el => accumulateOffsetTop( el ) - 100 )
setHeadings( { titles, nodes, minDepth, startingOffsets } )
}, [headingSelector, getTitle, getDepth] )
const scrollHandler = throttle( () => {
const { titles, nodes } = headings
const offsets = nodes.map( el => accumulateOffsetTop( el ) )
const activeIndex = offsets.findIndex(
offset => offset > window.scrollY + 120
)
setActive( activeIndex === -1 ? titles.length - 1 : activeIndex - 1 )
}, throttleTime )
useEventListener( `scroll`, scrollHandler )
...
}
Struggling with setting the correct types for the parameters passed to accumulateOffsetTop
. Any suggestions?