如何在自定义钩子中修复打字稿错误

时间:2020-08-02 08:40:35

标签: javascript reactjs typescript react-hooks

我在带有打字稿的项目中使用了这个ResizeObserver钩子


const useResizeObserver = () => {
  const [entry, setEntry] = useState<ResizeObserverEntry>();
  const [node, setNode] = useState<Element | null>(null);
  const observer = useRef<ResizeObserver | null>(null);

  const disconnect = useCallback(() => {
    const { current } = observer;
    if (current) {
      current.disconnect();
    }
  }, []);

  const observe = useCallback(() => {
    observer.current = new ResizeObserver(([entry1]) => setEntry(entry1));
    if (node) {
      observer.current.observe(node);
    }
  }, [node]);

  useLayoutEffect(() => {
    observe();
    return () => disconnect();
  }, [disconnect, observe]);

  return [setNode, entry];
};
const [node, entry] = useResizeObserver();
<div ref={node}>content</div>

当我在组件中使用此挂钩时,出现此错误

类型'Dispatch > | ResizeObserverEntry | undefined'不能分配给'string | ((实例:HTMLTableHeaderCellElement | null)=> void)| RefObject |空|未定义”。 类型'ResizeObserverEntry'不可分配给'string | ((实例:HTMLTableHeaderCellElement | null)=> void)| RefObject |空|未定义”。 在“ ResizeObserverEntry”类型中缺少属性“当前”,但在“ RefObject”类型中是必需的。

已修复帮助

2 个答案:

答案 0 :(得分:1)

您将返回# >>> conda initialize >>> # !! Contents within this block are managed by 'conda init' !! # these should already be in the PATH, but re-adding them wont hurt... export PATH="/bin:/usr/bin:/sbin:/usr/sbin:$PATH" # add other directories to the PATH here remembering to append (previous) PATH at the end PATH="/Users/arif/Library/Python/2.7/bin:$PATH" PATH="/usr/local/opt/ruby/bin:$PATH" PATH="/Library/Frameworks/Python.framework/Versions/3.8/bin:$PATH" PATH="/Applications/Postgres.app/Contents/Versions/latest/bin:$PATH" echo “source /usr/local/bin/virtualenvwrapper.sh” >> ~/.bash_profilesource /usr/local/bin/virtualenvwrapper.sh 作为return数组中的第一个元素,并尝试将其用作TableHeader setNode

ref不能用作setNode,请参见here,了解如何使用裁判

答案 1 :(得分:1)

我发现问题出在我们混合数组[setNode, entry]时来自打字稿推断为联合类型。因此,为了解决此问题,您只需将其设置为固定返回数组,如下所示:

return [setNode, entry] as const;

注意:仅在v3.4 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions

中具有此const断言