Friday, 22 July 2022

How can I preserve generics on a React higher-order component?

Let's say I want to use the React higher-order component pattern to transform a subset of my props before they hit my component:

type UpstreamProps<X> = {
    foo?: number
    bar?: string
    baz:  X
}

type DownstreamProps<X> = {
    foo: number
    bar: string
    baz: X
    bix: string
}

function transform<X>(props: UpstreamProps<X>): DownstreamProps<X> {
    return {
        ...props,
        foo: props.foo || 0,
        bar: props.bar || '(unknown)',
        bix: `${props.foo}-${props.bar}-bix`
    }
}

At the widget definition, I want to use downstream (strict) props:

function Parent<X>(props: DownstreamProps<X> & {formatter: (x: X) => string}) {
    return (
        <>
            foo = {props.foo}
            bar = {props.bar}
            baz = {props.formatter(props.baz)}
            bix = {props.bix}
        </>
    )
}

At the call site, I should be able to pass in upstream (optional) props:

<WrappedParent<number>
    baz={22}
    formatter={(x: number) => `my number squared is ${Math.pow(x, 2)}`}
/>

This is as close as I've gotten to writing the higher-order component, but I can't get it to play well with the generics on the Parent/WrappedParent:

function withDownstreamProps<X, OtherProps>(
    WrappedComponent: React.ComponentType<DownstreamProps<X> & OtherProps>
) {
    return function({foo, bar, baz, ...otherProps}: UpstreamProps<X> & OtherProps) {
        return (
            <WrappedComponent
                {...otherProps}
                {...transform({foo, bar, baz})}
            />
        )
    }
}

export default withDownstreamProps(Parent) // doesn't keep generics

How can I write and/or use my higher-order component wrapper to preserve the generics on the WrappedParent?



from How can I preserve generics on a React higher-order component?

No comments:

Post a Comment