【问题标题】:Type error with HOC in React and TypeScriptReact 和 TypeScript 中的 HOC 类型错误
【发布时间】:2018-12-29 20:28:00
【问题描述】:

我正在尝试在 React 和 TypeScript 中实现 HOC,但遇到类型错误。

这是 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)

有人有什么想法吗?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您的类型似乎不匹配:您的 HOC 的返回类型为:React.ComponentType&lt;P &amp; IProps&gt;,但您实际返回的函数类型为 (props: IProps) =&gt; React.ReactNode。如果你做到了(props: P &amp; IProps) =&gt; 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 中最容易做到的事情,所以我非常谨慎地使用它们。

    【讨论】:

      猜你喜欢
      • 2019-01-22
      • 2019-05-02
      • 2018-12-27
      • 2022-11-25
      • 2022-01-18
      • 1970-01-01
      • 2022-06-21
      • 2016-10-09
      • 1970-01-01
      相关资源
      最近更新 更多