Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Correct TypeScript types for passing children props through a React higher order component

$
0
0

Consider the following code, containing a higher order component, a functional component, and a component created using the HOC and our functional component:

interface InjectedProps {  someProp?: number;}const myHoc = <P extends {}>(  Component: ComponentType<P>) => ({someProp, ...props}: P & InjectedProps) => {  return <Component {...props as P} />;}const MyComponent = (props: {children?: React.ReactNode}) => {  return <div>{props.children}</div>;};const WrappedComponent = myHoc(MyComponent);

However, when we try and use this new WrappedComponent:

return (<WrappedComponent><h1>Hello</h1><h2>World</h2></WrappedComponent>);

We end up with the error: Type '{ children: Element[]; }' has no properties in common with type 'IntrinsicAttributes & InjectedProps'..

This can be solved by injecting the children prop into the props of the HOC, like so;

interface InjectedProps {  someProp?: number;  children?: React.ReactNode;}

However, we now have the problem of all wrapped components can now take on children, even when they could previously not.

My question is, what is the proper typing for a higher order component which passes down the children in the wrapped component?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>