hand sketched logo of electrons orbiting a nucleus

TIL: Typing React Rest Props

Quick, show me the code!

import { ComponentProps, ComponentType } from 'react';

type Props<C extends ComponentType<any>> = {
  Component: C;
} & ComponentProps<C>;

const FancyComponent = <C extends ComponentType<any>>({
  Component,
  ...rest
}: Props<C>) => {
  return <Component {...rest} />;
};

Ok, what's going on here?

Props<C> is a generic type that takes a component type C and returns a type that is a record with a key "component" that takes value C then we union that with ComponentProps<C>

ComponentProps<C> represents the record of props that a component C takes.