简体   繁体   English

什么打字稿类型用于函数参数?

[英]What typescript type use for function argument?

When onClick is triggered, the pressed HTML element (which is an <svg> element) is passed to handleClick as an argument (the argument is called "pressedElement").onClick被触发时,被按下的 HTML 元素(它是一个<svg>元素)作为参数传递给handleClick (该参数称为“pressedElement”)。 Since I've assigned to it any type and using any is considered a bad practice, I'd like to replace any by another Typescript type.由于我已将any类型分配给它,并且使用any被认为是一种不好的做法,因此我想将any替换为另一种 Typescript 类型。 What type should I use instead of using any ?我应该使用什么类型而不是使用any

This is the code of component:这是组件的代码:

import useScrollTrigger from '@material-ui/core/useScrollTrigger';
import Zoom from '@material-ui/core/Zoom';
import './Catalog.scss';
  
  const ScrollTop = (props: any) => {
    const { children, window } = props;
    const trigger = useScrollTrigger({
      target: window ? window() : undefined,
      disableHysteresis: true,
      threshold: 100,
    });
  
    const handleClick = (pressedElement: any) => {
      
      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)} 
          role="presentation" 
          className="scrollTop"
        >
          {children}
        </div>
      </Zoom>
    );
  }

  export default ScrollTop;

The first parameter of the onClick event is React.FocusEvent and your destructuring target whos type is EventTarget & HTMLInputElement. onClick 事件的第一个参数是 React.FocusEvent 和类型为 EventTarget & HTMLInputElement 的解构目标。

I have replicated your code on this codesandbox you can see that the types work and hovering on them shows you the type https://codesandbox.io/s/snowy-cloud-jlqwx?file=/src/Component.tsx我已经在这个 codeandbox 上复制了您的代码,您可以看到这些类型有效,将鼠标悬停在它们上会显示类型https://codesandbox.io/s/snowy-cloud-jlqwx?file=/src/Component.tsx

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM