TypeScript conditional types: Extract component props type from react component

I'd suggest to use React.ComponentType, because it will also include functional components:

type ExtractProps<TComponentOrTProps> =
  TComponentOrTProps extends React.ComponentType<infer TProps>
    ? TProps
    : TComponentOrTProps;

There's a built-in helper for that

type AnyCompProps = React.ComponentProps<typeof AnyComp>

And it also works for native DOM elements:

type DivProps = React.ComponentProps<"div">

https://stackoverflow.com/a/55005902/82609


It's a pretty straight forward application of conditional types and their inference behavior (using the infer keyword)

interface TestProps {
    foo: string;
}

class TestComponent extends React.Component<TestProps, {}> {
    render() { return null; }
}

type ExtractProps<TComponentOrTProps> = TComponentOrTProps extends React.Component<infer TProps, any> ? TProps : TComponentOrTProps;

type a = ExtractProps<TestComponent> // type a is TestProps
type b = ExtractProps<TestProps>     // type b is TestProps