简体   繁体   中英

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 ?

The generic type you want to assign to the WrappedParent should be given to the withDownstreamProps HOC not to the resulting component:

export default withDownstreamProps<number>(Parent)

Now the type of the baz property in the WrappedParent will be number .

If my answer was helpful an upvote would be appreciated.

Would something like that work for your case?:

type Wrapped<X, Other> = React.ComponentType<Output<X> & Other>

function withDownstreamProps<C extends Wrapped<any, any>>(
    WrappedComponent: C
) {
    return function<X, OtherProps>({foo, bar, baz, ...otherProps}: Input<X> & OtherProps) {
        return (
            <WrappedComponent
                {...otherProps}
                {...transform({foo, bar, baz})}
            />
        )
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM