Writing React Component which receives generic props. In class component way, it's easy:
interface TableProps<D> {
data: D
}
class Table<D> extends React.Component<TableProps<D>> { }
But, in function component way, I have no idea:
// can't figure out a way to define high order generic.
const Table2: <D extends {}> React.SFC<TableProps<D>> = ({ data }) => { }
How to correct it?
You don't have to explicitly type it as React.FC to get a type that works as expected. (It seems fairly common to write extends {} but I think extends any communicates the actual meaning better and works just as well.)
const Table = <D extends any>({ data }: TableProps<D>): ReactElement => <div>{data}</div>;
The fact that it is compatible with React.FC can be seen by the following type evaluating to true:
type Dummy = typeof Table extends React.FC<any> ? true : false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With