Typescript 和 useRef 钩子导致类型错误

Typescript and useRef hook causing type error

我制作了一个自定义复选框组件来以不同方式处理事件,代码如下:

const DoubleClickCheckbox = ({ filter, handleDoubleClick, handleSingleClick }: DCCheckboxProps) => {
  const delay = 400;
  const timer = useRef(null);

  const classes = useStyles();
  const flags = useFlags();

  useEffect(() => {
    return () => {
      timer.current && clearTimeout(timer.current);
    };
  }, []);

  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  const onClick = (e) => {
    if (flags.csRequireFilters) {
      e.stopPropagation();
      handleSingleClick(filter);
      return;
    }

    switch (e.detail) {
      case 1:
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        timer.current = setTimeout(() => {
          handleSingleClick(filter);
        }, delay);
        break;
      case 2:
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        clearTimeout(timer.current);
        handleDoubleClick(filter);
        break;
      default:
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        clearTimeout(timer.current);
        return;
    }
  };

  return (
    <div className={classes.filter} onClick={onClick} onKeyDown={() => {}} role="button" tabIndex={0}>
      <Checkbox
        label={filter.label}
        className={classes.checkbox_custom}
        checked={filter.selected}
        checkedIcon={filter.mandatory ? <Icons.CheckboxDoubleClick /> : <Icons.CheckboxSingleClick />}
      />
    </div>
  );
};

我想转储我的 eslint-disable-next-line @typescript-eslint/ban-ts-commentts-ignore

如果我重写我的代码,它会如下所示,我会收到打字稿错误:

  case 1:
    timer.current = setTimeout(() => {
      handleSingleClick(filter);
    }, delay);
    break;

错误是:Type 'Timeout' is not assignable to type 'null'. 我试过各种其他技巧,例如:const timer = useRef<React.MutableRefObject<ReturnType<typeof setTimeout>>>(null);.

也没用。

请指教

我认为问题在于 useRef(null) 隐式地将其类型设置为 null。您应该将其定义为 const timer = useRef<null | () => void>(null)

好像你的 ref 可以是 nullnumberReturnType<typeof setTimeout>number):

const timer = React.useRef<number | null>(null)