Generic React components in TypeScript/JSX?

Carl Patenaude Poulin picture Carl Patenaude Poulin · Jul 16, 2016 · Viewed 10.7k times · Source

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?

Answer

Jono Job picture Jono Job · Jul 19, 2018

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:

class GenericComponent<P> extends React.Component<P> {
    internalProp: P;
}
type Props = { a: number; b: string; };

const x = <GenericComponent<Props> a={10} b="hi"/>; // OK
const y = <GenericComponent<Props> a={10} b={20} />; // Error

Just thought it worth mentioning for anyone who ends up here via the question title.