我正在尝试在我的 React 项目中使用 Typescript,但在获取我的 HOC 功能的类型时遇到了困难。这是一个最小的示例来展示我遇到的问题:
const withDecorator =
(Wrapped: React.ComponentType): React.ComponentClass =>
class withDecorator extends Component {
render() {
return <Wrapped {...this.props} />
}
}
@withDecorator
class Link extends Component<object, object> {
render() { return <a href="/">Link</a> }
}
这将返回错误:
'Unable to resolve signature of class decorator when called as an expression.
Type 'ComponentClass<{}>' is not assignable to type 'typeof Link'.
Type 'Component<{}, ComponentState>' is not assignable to type 'Link'.
Types of property 'render' are incompatible.
Type '() => string | number | false | Element | Element[] | ReactPortal | null' is not assignable to type '() => Element'.
Type 'string | number | false | Element | Element[] | ReactPortal | null' is not assignable to type 'Element'.
Type 'null' is not assignable to type 'Element'.'
我真的不明白为什么会发生这个错误。我一定做错了什么。一旦我介绍了道具,事情就会变得更加棘手。
我将非常感谢正确的解决方案,但我也很想了解为什么会首先出现此错误。
谢谢!