代码之家  ›  专栏  ›  技术社区  ›  Carl Rippon

React和TypeScript中的HOC类型错误

  •  0
  • Carl Rippon  · 技术社区  · 7 年前

    我试图在React和TypeScript中实现一个HOC,但是得到了一个类型错误。

    import * as React from "react";
    
    interface IProps {
      loading: boolean;
    }
    
    const withLoader = <P extends object>(
      Component: React.ComponentType<P>
    ): React.ComponentType<P & IProps> => ({ loading, ...props }: IProps) =>
      loading ? (
        <div className="overlay">
          <div className="loader" />
        </div>
      ) : (
        <Component {...props} />
      );
    export default withLoader;
    

    反应类型的版本为:

    "devDependencies": {
      "@types/react": "^16.7.18",
      "@types/react-dom": "^16.0.11",
      ...
    }
    

    react的版本为:

    "dependencies": {
      "react": "^16.7.0",
      "react-dom": "^16.7.0",
      ...
    }
    

    我得到的错误是:

    类型“{}”不可分配给类型“P”。ts(2322)

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   Stuart Bourhill    7 年前

    似乎您的类型不匹配:您的HOC的返回类型为: React.ComponentType<P & IProps> 但是您实际返回的函数是 (props: IProps) => React.ReactNode . 如果你成功了 (props: P & IProps) => React.ReactNode 它会停止抱怨。也就是说,我输入这个HOC的方式是:

    function withLoader<P extends IProps>(Component: React.ComponentType<P>) {
      const Inner: React.FC<P> = props => { // the return type is inferred by the compiler
        if (props.loading) {
          return (
            <div className="overlay">
              <div className="loader" />
            </div>
          )
        }
        return <Component {...props} />
      }
    
      return Inner // return type is React.FC<P>
    }
    

    false 一旦它到达您的组件。

    最后的想法 当前位置我发现自己正在远离HOC,因为它们很难打字。如果您关心类型安全,您可能更喜欢只使用渲染道具(可能不适用于此用例)或在组件中手动处理它。它可能更详细,但更容易键入,而且更明确。我的意见是:HOC在TypeScript中并不是最容易做到的,所以我很少使用它们。