Typescript React HOC 错误与 hoist-non-react-statics

Typescript React HOC error with hoist-non-react-statics

我正在使用 react 和 typescript 以及 hoist-non-react-statics 并尝试创建一个 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<any>.

编辑:typescript@2.9.2 @types/react@16.8.4 @types/hoist-non-react-statics@3.0.1

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

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