【发布时间】: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<any>。
编辑:打字稿@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