Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a React Class Component with generic props to Function Component in Typescript?

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?

like image 797
Zheeeng Avatar asked Feb 10 '26 17:02

Zheeeng


1 Answers

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;
like image 132
AndyO Avatar answered Feb 13 '26 17:02

AndyO