Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript React: How do you pass a generic to a React.ComponentProps<typeof ComponentWithGenericProps>?

Context

I have a Tree component and its props are defined using a generic type T:

type ITreeProps<T> = ICollapsibleTreeProps<T> | INonCollapsibleTreeProps<T>;

My component is defined as so:

const Tree = <T extends {}>(props: ITreeProps<T>) => { /* ... */ };

Problem

Now if I create a type using React.ComponentProps (in a separate file importing the Tree component)

type ITreeComponentProps = React.ComponentProps<typeof Tree>;

The generic is automatically considered as {}, so the resulting type is:

type ITreeComponentProps = ICollapsibleTreeProps<{}> | INonCollapsibleTreeProps<{}>

Question

Is there a way to pass a generic to React.ComponentProps so I can specify my own type instead of having it forced to {}?

my intuition was then to do the following, which does not work, although I expected the generic type to come without having to specify a T:

type ITreeComponentProps<T> = (React.ComponentProps<typeof Tree>)<T>;

with the resulting type being

type ITreeComponentProps<T> = ICollapsibleTreeProps<T> | INonCollapsibleTreeProps<T>

So I can use it as so:

const someFunction = <T extends {}>(p: ITreeComponentProps<T>) => { /* ... */ }; 

Temporary Solution

Until I find the solution, the only way I can use it as the last snippet is to export the ITreeProps and import it in my other file instead of using React.ComponentProps. However, I don't usually like exporting my component props as a personal preference.

like image 869
MaxiJonson Avatar asked Nov 06 '22 11:11

MaxiJonson


1 Answers

typeof Tree<Foo>

This is not possible in TypeScript https://github.com/microsoft/TypeScript/issues/204

TL;DR typeof works with values and Tree<Foo> is a type, despite that Tree itself is a value.

P.S: we're also using types exported along with components

P.P.S: here is the maintainers discouraging usage of React.ComponentProps https://github.com/DefinitelyTyped/DefinitelyTyped/pull/34899#issuecomment-485815000

like image 176
amankkg Avatar answered Nov 15 '22 05:11

amankkg