TypeScript conditional types: Extract component props type from react component

Dynalon picture Dynalon · Apr 29, 2018 · Viewed 8.6k times · Source

Using TypeScript 2.8 new conditional generic type feature, is it possible to extract the TProps of a React.ComponentType<TProps> component? I want a type that can either work on the ComponentType or the TProps itself, so you can - as a developer - pass either of both:

For example:

interface TestProps {
    foo: string;
}

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

// now I need to create a type using conditional types so that
// I can pass either the component or the props and always get the 
// TProps type back
type ExtractProps<TComponentOrTProps> = /* ?? how to do it? */

type a = ExtractProps<TestComponent> // type a should be TestProps
type b = ExtractProps<TestProps>     // type b should also be TestProps

Is this possible, and can anybody provide a solution?

Answer

Sebastien Lorber picture Sebastien Lorber · Mar 18, 2019

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