You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript中点击事件传入DOM元素作为函数入参应使用什么类型?

你可以把pressedElement参数的any类型直接替换为Element,这个类型完全适配你的使用场景:

  • 你场景中用到的<svg>元素和所有HTML元素都继承自Element接口,兼容性足够
  • Element接口自带你代码中用到的ownerDocument属性,不会触发TypeScript类型报错

如果想要更严谨,贴合TypeScript原生的事件对象类型定义,可以补充类型守卫处理边界情况:

const handleClick = (pressedElement: EventTarget | null) => {
  // 非Element类型的target直接终止逻辑,避免报错
  if (!(pressedElement instanceof Element)) return;

  const anchor = (pressedElement.ownerDocument || document).querySelector('#back-to-top-anchor');
  if (anchor) {
    anchor.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }
};

顺便你代码里组件props的any类型也可以同步优化,完整优化后代码如下:

import useScrollTrigger from '@material-ui/core/useScrollTrigger';
import Zoom from '@material-ui/core/Zoom';
import { PropsWithChildren } from 'react';
import './Catalog.scss';
  
const ScrollTop = (props: PropsWithChildren<{ window?: () => Window }>) => {
  const { children, window } = props;
  const trigger = useScrollTrigger({
    target: window ? window() : undefined,
    disableHysteresis: true,
    threshold: 100,
  });

  const handleClick = (pressedElement: Element) => {
    const anchor = (pressedElement.ownerDocument || document).querySelector('#back-to-top-anchor');
    if (anchor) {
      anchor.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  };

  return (
    <Zoom in={trigger}>
      <div 
        onClick={({ target }) => handleClick(target as Element)} 
        role="presentation" 
        className="scrollTop"
      >
        {children}
      </div>
    </Zoom>
  );
}

export default ScrollTop;

上面代码里给target加了as Element类型断言,因为TypeScript原生定义的点击事件target类型为EventTarget | null,而我们确定此处触发点击的一定是DOM元素,所以直接断言即可。

内容的提问来源于stack exchange,提问作者rumon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 12:39:03