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>) => { /* ... */ };
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<{}>
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>) => { /* ... */ };
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With