How to inject prop types into component that is wrapped by hoc

144 Views Asked by At

I have a HOC like this

import React, {useEffect, useMemo, useState} from 'react'

interface WindowSize {
    width: number,
    height: number
}

export function WithWindowSize <T>(Component: React.ComponentType<T>) {
    return function WithComponent(props: T) {
        const [windowSize, setWindowSize] = useState({} as WindowSize)

        useEffect(() => {
            ...
        }, [])


        return <Component
            {...props}
            windowSize={windowSize}/>
    }
}

export default WithWindowSize;

Now I want to use this HOC.

interface FooProps {
    headline: string,
    value: string | number,
}

const Foo = ({headline, value, windowSize}: FoooProps & WindowSize) => {
    return ...
}

export default WithWindowSize(Foo);

This gives me

Property 'windowSize' does not exist on type 'FooProps & WindowSize'.

How would I inject the prop type WindowSize into Foo? I would think the best way is to do it in the HOC, so that I do not have to do it every time I wrap something with WithWindowSize.

1

There are 1 best solutions below

2
Victor Santizo On BEST ANSWER

I would just include the windowSize as an optional property in the FooProps interface, because there is no way for Foo (or any other component) to know that it is going to be used within a HOC

interface WindowSize {
    width: number,
    height: number
}

interface FooProps {
    headline: string,
    value: string | number,
    windowSize?: WindowSize
}

const Foo = ({headline, value, windowSize}: FooProps) => {
    return ...
}