When I apply withRouter
as a decorator to a component, such as
@withRouter
@observer
// observer is mobx decorator
export default class UserInfo extends React.Component<any> {
render() {
return (
<div>1</div>
)
}
}
An error related to type checking occurs:
(10,1): Unable to resolve signature of class decorator when called as an expression.
Type 'ComponentClass<Pick<any, string | number | symbol>, any>' is not assignable to type 'typeof UserInfo'. Type 'Component<Pick<any, string | number | symbol>, any, any>' is not assignable to type 'UserInfo'. Types of property 'render' are incompatible. Type '() => ReactNode' is not assignable to type '() => Element'.
Type 'ReactNode' is not assignable to type 'Element'.
Type 'undefined' is not assignable to type 'Element'.
Why is the type of <div>1</div>
considered as Element
, instead of ReactNode
?
I noticed that the definition of render function is render(): ReactNode
, so why does TypeScript interpret it as an Element
?
How can this error be resolved?
I attempted to add a return type to render()
.
@withRouter
@observer
export default class UserInfo extends React.Component<any> {
render(): React.ReactNode {
return (
<div>1</div>
)
}
}
// or
@observer
class UserInfo extends React.Component<any> {
render(): React.ReactNode {
return (
<div>1</div>
)
}
}
export default withRouter(UserInfo)
This solution works, but it lacks elegance. I prefer using withRouter
as a decorator. Is there a better way to achieve this?