Help with Typescript and children types
See original GitHub issueHey there,
I have strictly typed my children prop for my render prop components. Now, I’m trying to integrate react-adopt@0.6.0
, and I’m having some issues with those typings.
I have a render prop component that looks like this:
//Component.tsx
export interface Props {
children: (track: Track) => JSX.Element
}
export default function({ children }: Props) {
return children((event, data) => {
...
})
}
When I compose that with react-adopt, like this:
const Composed = adopt<RenderProps, ComposedProps>({
track: () => (
<Component/>
),
...
I get a typescript error that children is missing.
If I type the children prop in the Component in the same way it’s typed in react-adopt
:
((track: Track) => JSX.Element | null) | undefined
, I need to update the component to return children && children(...)
to satisfy the compiler.
At that point I start receiving this warning inside the composed function, for my Component:
JSX element type 'Element | null | undefined' is not a constructor function for JSX elements. Type 'undefined' is not assignable to type 'ElementClass'.
When I assume I need to follow your typescript example more closely, I tried:
const Composed = adopt<RenderProps, ComposedProps>({
track: ({ render}) => (
<Component> {(track => render({track})} </Component>
...
This returns the typescript error: Cannot invoke an object which is possibly 'undefined'
.
I’ve tried again typing the Component children type to include undefined, as per react-adopt
, as well as updating the composed Component to use render && render(...)
, returns the above error again on the component being composed: JSX element type 'Element | null | undefined' is not a constructor function for JSX elements. Type 'undefined' is not assignable to type 'ElementClass'.
I normally wouldn’t bother maintainers with typescript questions, but since you’ve written the source in typescript I thought this might have been a problem that you ran into and accounted for, in which case I’m sure I’m missing something simple here!
I’d appreciate any help getting around this issue! Thanks in advance for your time 😄
Issue Analytics
- State:
- Created 5 years ago
- Comments:12 (1 by maintainers)
Did you try to use your
children
function as an optional type like that:When this happened with me that was my solution ✌️
@damassi here is the proof of concept for the types:
Currently it only support passing a function that accepts
render
, but I don’t foresee any issues extending it to support components with render props.If you use these types all you need to do is call
adopt({...})
and it will infer both the render props types and the input props into the composed component.So far I’ve also only typed the
adopt
function, not the component, although I also don’t see an issue typing the component in the same manner.