This article shows how to combine React forwardRef with TypeScript generics to build a reusable, type‑safe Table component while preserving full type inference using type assertions.
Written by: Chia1104 CC BY-NC-SA 4.0
Since React's forwardRef is a HOC (Higher Order Component), we can't directly write generics inside the component. The most common scenario where I need to use generics and also reference internal methods is the Table component.
If we want to create a type-safe component, we can use the following approach:
export interface Props<TData> {
data: TData[];
}
export interface Ref<TData> {
table: Table<TData>;
}
const DataTableWithGeneric<TData>(
props: Props<TData>,
ref: Ref<TData>
) => {
React.useImperativeHandle(ref, () => ({
table,
}));
const table = useReactTable({
data: props.data,
});
return (
// ...table component
)
}
const Forwarded = React.forwardRef(DataTableWithGeneric) as <TData>(
props: Props<TData> & {
ref?: React.ForwardedRef<Ref<TData>>;
},
) => ReturnType<typeof DataTableWithGeneric>;
export const DataTable = Forwarded;