I’ve written a react HOC, just like this:
type Props<T> = {
value: T
}
function HOC<P extends Props<any>>(Comp: ComponentType<P>) {
type ValueType = P extends Props<infer T> ? T : never
type Example = Omit<P, 'value'> & { value1: ValueType }
return function CompWithHOC(props: Example) {
const { value1, ...rest } = props
const compProps: P = { // here
...rest,
value: value1
}
return <Comp {...compProps}></Comp>
}
}
The compiler reports compProps
has a type error. The message is
Type ‘Omit<Example, “value1”> & { value: ValueType; }’ is not assignable to type ‘P’.
‘Omit<Example, “value1”> & { value: ValueType; }’ is assignable to the constraint of type ‘P’, but ‘P’ could be instantiated with a different subtype of constraint ‘Props’
How can I write a good HOC in typescript?
zhuoxin yuan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
import React, { ComponentType } from 'react';
type Props<T> = {
value: T;
};
function HOC<P extends Props<any>>(Comp: ComponentType<P>) {
type ValueType = P extends Props<infer T> ? T : never;
type Example = Omit<P, 'value'> & { value1: ValueType };
return function CompWithHOC(props: Example) {
const { value1, ...rest } = props;
const compProps = {
...rest,
value: value1
} as P;
return <Comp {...compProps}></Comp>;
};
}
export default HOC;