Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript conditional types: Extract component props type from react component

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?

like image 562
Dynalon Avatar asked Apr 29 '18 08:04

Dynalon


People also ask

Can we pass props to the parent component?

React components use props to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, and functions.

What is Areact component?

Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML. Components come in two types, Class components and Function components, in this tutorial we will concentrate on Function components.


2 Answers

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

like image 89
Sebastien Lorber Avatar answered Sep 21 '22 14:09

Sebastien Lorber


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;
like image 22
SleepWalker Avatar answered Sep 22 '22 14:09

SleepWalker