-
Notifications
You must be signed in to change notification settings - Fork 12.8k
type annotation for higher order react component #6559
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
See #5887 for an example of this. There is currently an issue with the approach outlined there but it is fixed in 1.8.0 nightly. |
What you want is this: const HigherOrderComponent = (component: typeof React.Component) => {
return class extends component<any, any> {
render() {
return super.render();
}
};
}; |
This worked and is very readable. Thanks Ryan. |
@RyanCavanaugh Doesn't that lose typing on the returned class? |
class Component<T, U> {
render() { }
}
const React = {
Component
}
const HigherOrderComponent = (component: typeof React.Component) => {
return class extends component<any, any> {
render() {
return super.render();
}
foo = 'bar';
};
};
const NewClass = HigherOrderComponent(React.Component);
const p = new NewClass();
p.foo; // string |
@kitsonk I should have been more specific--doesn't it lose React Component props typing? (No one is instantiating React Components via I think this is an issue for folks using JSX |
The JSX tag is mapped to a constructor. It shouldn't lose its types, being instaniated programatically or by some JSX tag. |
Well it does because the class being returned specifies the props to be type
If you put the correct types in here then the props should end up properly typed. However, having tried it, it does seem difficult to use the 'inheritance approach' with base components which are not generic. I was able to get it working using the 'composition approach' however:
|
@frankwallis That looks good, but for some reason I get I haven't been able to figure out a workaround |
this is how i've approached it until the new spread proposal goes live: this wraps my routes entry component:
Here I'm wrapping my entry with a
Then in my
It's certainly not perfect but it does work :) |
I am trying to figure out type annotation for higher order react components. Here's my code
typescript compiler throws following error
Error:(23, 24) TS2507: Type 'any' is not a constructor function type
I tried couple of annotation such as
<any, any>
,<T extends React.Component<any, any>>
. None of them is passing through compilation.The text was updated successfully, but these errors were encountered: