What You'll Learn
You'll learn how to write generic higher-order components (HOCs) that wrap other components while preserving and extending their prop types safely.
The HOC Challenge
Higher-order components are functions that take a component and return an enhanced version. The tricky part? You need to preserve the original component's props while potentially adding new ones. Without generics, you'd lose type safety completely.
Think of it like gift-wrapping: you want to add decorative paper without losing track of what's actually inside the box.
Core Pattern: Generic HOC Typing
The pattern uses a generic type parameter to capture the wrapped component's props:
type WithLoading<P> = P & {
isLoading: boolean;
};
function withLoading<P>(Component: (props: P) => void): (props: WithLoading<P>) => void {
return (props: WithLoading<P>) => {
if (props.isLoading) {
console.log("Loading...");
return;
}
const { isLoading, ...rest } = props;
Component(rest as P);
};
}
Here, <P> captures whatever props the original component expects, then WithLoading<P> adds the isLoading property on top.
Using the Generic HOC
type UserProps = { name: string; age: number };
const User = (props: UserProps) => {
console.log(`${props.name}, ${props.age}`);
};
const UserWithLoading = withLoading<UserProps>(User);
// TypeScript knows you need: name, age, AND isLoading
UserWithLoading({ name: "Alice", age: 30, isLoading: false });
The generic ensures the wrapped component remembers it needs name and age, while the HOC adds its own requirement.
Key Takeaway: Generic HOCs use type parameters to capture the original component's props, then use intersections to combine them with injected props, preserving full type safety through the wrapping process.