I would like to create pluggable React components. Components are resolved by their class names, so I am naturally drawn to generics; but this doesn't seem to work.
class Div<P, S, C extends React.Component> extends React.Component<void, void> {
render() {
return (
<div>
<C /> // error: Cannot find name 'C'.
</div>
);
}
}
Is there an alternative way to write pluggable TypeScript components?
The accepted answer for this question still stands, due to TypeScript types being erased, however as of Typescript 2.9, generic JSX components are supported
The example provided is:
Just thought it worth mentioning for anyone who ends up here via the question title.
This isn't possible to do using generics, though it's not clear why you would want to use generics for this problem rather than just providing the inner element using the normal
props
mechanism.The reason is that types are erased, so you need to provide the class constructor to the class so that it has a reference to the value to instantiate in
C
. But there's no place other than the JSXprops
(orstate
or whatever you need to do) for you to pass in that value.In other words, instead of writing
You should write
and consume it in your
render
asAs an aside, the correct constraint is
new() => React.Component
rather thanReact.Component
-- remember that the things you write in the JSX (<Div>
, etc) are the constructors for classes, not the class instances.