I'm trying to create a generic higher order component and type safety is not checked. When doing the same but in a not generic way, the type safety is checked as expected.
interface IBaseProps {
baseValue?: string;
}
const Base = (props: IBaseProps) => {
return <span>{"value: " + props.baseValue}</span>;
};
interface IExtraProps {
extraValue?: string;
}
const foo = <T extends IBaseProps>(
Element: React.ComponentType<T>
): React.ComponentType<T & IExtraProps> => (props: T & IExtraProps) => {
const baseValue = `${props.baseValue} extra value: ${props.extraValue}`;
return <Element {...props} baseValue={baseValue} />; // example
};
const bar = <T extends IBaseProps>(
Element: React.ComponentType<T>
): React.ComponentType<T & IExtraProps> => (props: T & IExtraProps) => {
return <Element {...props} baseValue={42} />; // NO error, why?
};
const baz = <T extends IBaseProps>(
Element: React.ComponentType<T>
): React.ComponentType<T & IExtraProps> => (props: T & IExtraProps) => {
return <Element {...props} unknownProp={42} />; // NO error, why?
};
const bag = (props:IBaseProps) => {
const baseValue = props.baseValue + ' augmented'
return <Base {...props} baseValue={42} />; // ok, error is detected
}
Demo can be found here
How to make Typescript check types correctly?