【问题标题】:Typescript React HOC error with hoist-non-react-staticsTypescript React HOC 错误与提升非反应静态
【发布时间】:2019-07-17 01:39:45
【问题描述】:

我正在使用 react 和 typescript 以及提升非反应静态并尝试创建一个 HOC。我已经将代码简化为一个人为的 HOC,它用 div 包装了组件。

const withWrapper = <TProps extends {}>(
  WrappedComponent: React.ComponentType<TProps>,
) => {
  const WithWrapper: React.FC<TProps> = (props: TProps) => (
    <div>
      <WrappedComponent {...props} />
    </div>
  )

  WithWrapper.displayName = `WithWrapper(${
    WrappedComponent.displayName || WrappedComponent.name || 'Component'
  })`

  return hoistNonReactStatics(WithWrapper, WrappedComponent)
}

但得到错误:

Argument of type 'ComponentType<TProps>' is not assignable to parameter of type 'ComponentType<any>'.
  Type 'ComponentClass<TProps, any>' is not assignable to type 'ComponentType<any>'.
    Type 'ComponentClass<TProps, any>' is not assignable to type 'FunctionComponent<any>'.
      Type 'ComponentClass<TProps, any>' provides no match for the signature '(props: any, context?: any): ReactElement<any, string | ((props: any) => ReactElement<any, string | any | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.

     return hoistNonReactStatics(WithWrapper, WrappedComponent)
                                              ~~~~~~~~~~~~~~~~

为什么这是无效的?让它通过的唯一方法是投射WrappedComponent as React.ComponentType&lt;any&gt;

编辑:打字稿@2.9.2 @types/react@16.8.4 @types/hoist-non-react-statics@3.0.1

【问题讨论】:

  • 您确定您使用的不是其他版本的 TypeScript 或某些类型吗?例如,如果您使用 Visual Studio Code,您可能需要选择项目中安装的 TypeScript 版本(而不是 IDE 中内置的版本)。

标签: reactjs typescript definitelytyped


【解决方案1】:

您的代码适用于typescript@3.3.1@types/react@16.8.4@types/hoist-non-react-statics@3.0.1

您的代码中唯一不正确的是使用单管道 (|) 而不是双管道。单管道用于按位或,而双管道用于短路——我相信你的意思是后者。

【讨论】:

  • 对不起,我应该添加打字稿版本:2.9.2。编辑过的 OP。感谢管道捕获,人为的示例错误。
  • 我认为升级 TS 是解决这个问题的方法。虽然我很想知道为什么完美的代码在 2.9.2 中失败
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 2020-03-05
  • 2018-09-11
  • 2019-01-22
相关资源
最近更新 更多