I am writing a higher order component for my React project using Typescript, which is basically a function that takes a React component as an argument and returns a new component that wraps around it.
However, since it works as expected, TS complains that "The return type of the exported function has or uses the private name" Anonymous Class ".
Function in question:
export default function wrapperFunc <Props, State> ( WrappedComponent: typeof React.Component, ) { return class extends React.Component<Props & State, {}> { public render() { return <WrappedComponent {...this.props} {...this.state} />; } }; }
The error is reasonable, since the return class of the wrapper function is not exported, and another module imports this function, unable to find out what the return value will be. But I can not declare the returned class outside this function, as it requires the package to pass an external function.
A trial version with an explicit type return typeof React.Component , as shown below, suppresses this error.
The function in question with an explicit return type:
export default function wrapperFunc <Props, State> ( WrappedComponent: typeof React.Component, ): typeof React.Component { // <== Added this return class extends React.Component<Props & State, {}> { public render() { return <WrappedComponent {...this.props} {...this.state} />; } }; }
However, I am not sure of the validity of this approach. Is this the right approach to solve this particular error in TypeScript? (Or am I creating unintended side effects elsewhere? Or is there any better way to do this?)
(Modify) Modify the quotation code as proposed by Daniel.