HaoSiong Ng
HaoSiong Ng

Reputation: 97

How to type an object that contains a React component as a property and also that component's props as another property?

Let's say I got an object that structured as follows:

{
  Component, //<--- the component
  props, //<--- the props of the component
}

I would like to create a generic type for this object so that it accepts a component and infer that component's props type as the props property.

This is the type I try to create by referring to this post and it doesn't as I expected.

type Object<P = {}> = {
  Component: React.ComponentType<P> | React.ElementType;
  props?: React.ComponentProps<typeof P>;
} & P;

My implementation

doSomething({
  Component: AnotherComponent,
  props: {
    ...// AnotherComponent's props
  }
})

doSomething is a function that accepts the object as a parameter.

I am very new to typescript and I couldn't find my answer on TS documentation. I will be very grateful if someone could guide me on this.

Upvotes: 1

Views: 1659

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187312

Create a generic interface where the props are the generic parameter, and then you construct the component type from those props.

interface WrapComponent<P> {
    Component: React.ComponentType<P>
    props: P
}

Now in your function just be sure to forward the generic parameter to the interface so the right prop types can be inferred:

function doSomething<P>({ Component, props }: WrapComponent<P>) {
    return <Component {...props} />
}

doSomething({
    Component: ({ a }: { a: number }) => <>{a}</>,
    props: { a: 123 },
})

See typescript playground for working example

Upvotes: 2

Related Questions