javascript / expert
Snippet
Type-Safe Higher Order Components (HOC)
Using TypeScript generics (P extends object) in HOCs ensures that the wrapped component retains its prop definitions while adding new functionality without type erosion.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
interface WithLoadingProps {isLoading: boolean;}function withLoading<P extends object>(Component: React.ComponentType<P>) {return function WappedComponent({ isLoading, ...props }: P & WithLoadingProps) {if (isLoading) return <Spinner />;return <Component {...(props as P)} />;};}
react
Breakdown
1
withLoading<P extends object>(Component: React.ComponentType<P>)
Uses a generic P to represent the original props of the passed component.
2
P & WithLoadingProps
Combines the original props with the new 'isLoading' prop using an intersection type.