Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Higher Order Component Types Issue

I am trying the following code. But the typescript error won't go away. Also, not sure whats the error even means.

type CounterProps = {
    counter: number
}

const WithCounter = <T extends CounterProps> (Component: React.ComponentType<T>) => {
    const ComponentWithCounter = (props: Omit<T, keyof CounterProps>) => {
        return <Component {...props} counter={23} />
    }
    return ComponentWithCounter
}

I am simply trying to inject a counter "number" props to my underlying component. It is giving the following error.

Type 'Omit<T, "counter"> & { counter: number; }' is not assignable to type 'IntrinsicAttributes & T'.
    Type 'Omit<T, "counter"> & { counter: number; }' is not assignable to type 'T'.
    'Omit<T, "counter"> & { counter: number; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'CounterProps'.ts(2322)

I followed this tutorial. I did notice that over there they have done {...props as T} while passing them.. but I don't understand why we need to do something like that.

like image 588
Avan Avatar asked Dec 29 '25 19:12

Avan


1 Answers

After spending hours on this, came up with this solution instead.

interface CounterProps {
    counter: number;
}

const withCounter = <T extends {}> (Component: ComponentType<T & CounterProps>) => {
    const InnerComponent: React.FC<T> = (props) => {
        return <Component {...props} counter={23} />
    }

    return InnerComponent;
}

like image 110
Avan Avatar answered Jan 01 '26 09:01

Avan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!