Reputation: 386
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.
Upvotes: 3
Views: 754
Reputation: 386
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;
}
Upvotes: 2
Reputation: 1619
Given your implementation WithCounter
can be called as below.
type InvalidType = {counter: number, invalidProperty: unknown}
const input: React.ComponentType<InvalidType> = ...
WithCounter(input)
But since InvalidType
isn't valid as input to Component
, the error is shown.
Upvotes: 1