Typescript - 滚动事件的 addEventListener 类型接口

Typescript - addEventListener type interface for scroll event

监听scroll事件时添加type接口的正确方法是什么


    onMounted(() => {
      ...
      // Call when mounted;
    
      document.addEventListener("scroll", (e: ScrollEvent) => {
        console.log(e); // Type interface of ScrollEvent
      });
    });

下面是一个示例,这是 Document: scroll event 的 MDN 页面。

TS Playground

type Coords = {
  x: number;
  y: number;
};

function getScrollCoordinates (): Coords {
  return {
    x: window.scrollX,
    y: window.scrollY,
  };
}

function writeScrollCoordinates (elementContainer: HTMLElement, coords: Coords): void {
  elementContainer.textContent = JSON.stringify(coords, null, 2);
}

function handleScroll (event: Event): void {
  //                   ^^^^^^^^^^^^
  // The scroll event is just an instance of the base Event class
  writeScrollCoordinates(document.getElementById('coords')!, getScrollCoordinates());
}

window.addEventListener('scroll', handleScroll);

示例:

"use strict";
function getScrollCoordinates() {
    return {
        x: window.scrollX,
        y: window.scrollY,
    };
}
function writeScrollCoordinates(elementContainer, coords) {
    elementContainer.textContent = JSON.stringify(coords, null, 2);
}
function handleScroll(event) {
    //                   ^^^^^^^^^^^^
    // The scroll event is just an instance of the base Event class
    writeScrollCoordinates(document.getElementById('coords'), getScrollCoordinates());
}
window.addEventListener('scroll', handleScroll);
body {
  --size: 10000px;
  height: var(--size);
  width: var(--size);
}

#coords {
  font-family: monospace;
  font-size: 2rem;
  position: fixed;
  top: 1rem;
  left: 1rem;
}
<pre><code id="coords">Scroll to see coordinates</code></pre>