typescript - v3.9.7
I have a HOC that pass additional props to the component:
import React from 'react';
interface IWithOwner {
owner: string;
}
type IWithoutOwner<T extends IWithOwner> = Omit<T, keyof IWithOwner> & {owner?: never};
// CORRECT
export function withOwnerOne<TProps extends IWithOwner>(Component: React.ComponentType<TProps>) {
const ComponentWithOwner: React.FunctionComponent<IWithoutOwner<TProps>> = (props) => {
return (
<Component
owner="Tom"
{...props}
/>
);
}
return ComponentWithOwner;
}
// ERROR
export function withOwnerTwo<TProps extends IWithOwner>(Component: React.ComponentType<TProps>) {
return class extends React.Component<IWithoutOwner<TProps>> {
render() {
return (
// '{ owner: string; } & Readonly<IWithoutOwner<TProps>> & Readonly<{ children?: ReactNode; }>'
// is assignable to the constraint of type 'TProps', but 'TProps' could be
// instantiated with a different subtype of constraint 'IWithOwner'.
<Component
owner="Tom"
{...this.props}
/>
)
}
}
}
withOwnerOne that uses Function component works correctly. While withOwnerTwo that uses class component has an error. Why do they work differently?