Just use as a generic of normal functions, Typescript will understand that it is an React component when you call it.
Thus:
interface Props<T> {
items: T[];
}
// ↓↓↓
function MyComponent<T>(props: Props<T>) {
return (
<>{JSON.stringify(props.items, null, 2)}</>
);
}
Note that you will not be able to use a Arrow Function using the type React.FC
, since the generic would have to come afterward. The guy React.FC
adds the property children
implicitly. So, if your component has to use that prop, just modify the interface Props
:
interface Props<T> {
items: T[];
children: React.ReactNode;
}
To define the generic in the component, use this notation:
<MyComponent<string> items={['A', 'B', 'C']} />
<MyComponent<number> items={[1, 2, 3]} />
In the end, you’ll have something like:
import React from 'react';
interface Props<T> {
items: T[];
}
function MyComponent<T>(props: Props<T>) {
return (
<>{JSON.stringify(props.items, null, 2)}</>
);
}
function MainComponent() {
return (
<>
<MyComponent<string> items={['A', 'B', 'C']} />
<MyComponent<number> items={[1, 2, 3]} />
</>
);
}
See working on Typescript playground.
Felipe, I was reading a PR on Github and I ended up remembering this question: https://github.com/facebook/create-react-app/pull/8177
– Luiz Felipe