ReactJS TypeScript render prop hide parameter

Viewed 22

How can I disable access to injected parameter in render prop, if a specific prop is not set to component that renders the render prop.

interface Test {
    test: string
}

interface ComponentProps {
    someProp?: Test,
    children: (params: {param1: boolean, param2: string}) => ReactElement
}

const Component = ({someProp, children}: ComponentProps) => {
    return children({
        param1: false,
        param2: 'test'
    })
}

Here how to disable param2 to be used if someProp is not provided to Component, with TypeScript. This should be invalid:

const instance = <Component>
    {
        ({param1, param2}) => <div>{param2}</div>
    }
</Component>

And those valid:

        // someProp is not set, so I can not use param2
       <Component>
            {
                ({param1}) => <div>static text</div>
            }
        </Component>

  
     // someProp is set, so I can use param2
     <Component someProp={{test: 'demo'}}>
            {
                ({param1, param2}) => <div>{param2}</div>
            }
    </Component>

I want to conditionally exclude param2 from the type, not from the value

1 Answers

If I understand the question correctly, you can conditionally render the children:

const Component = ({someProp, children}: ComponentProps) => {
    return !!someProp ? children({
        param1: false
    }) : children({
        param1: false,
        param2: 'test'
    })
}
Related