React And Typescript
Edit page
HomeTypeScript Crash Course
Installation
Examples
Class ComponentsFunctional ComponentsHigher Order Components (HOCs)Injected PropsHooksReact Router
ContributingReadme

Higher Order Components (HOCs)

Please note that this section uses the utility-types package since, as of May 2019, the helper functions were unavailable in TypeScript.

Injected Props

HOCs often inject props into wrapped components. In the below example, T is defined as the WrappedComponent props together with the

import { ComponentType } from 'react';
import { Diff } from 'utility-types';
export interface WithWoofStringProps {
woof: string;
}
export default function withWoofString<T extends WithWoofStringProps>(
WrappedComponent: ComponentType<T>
) {
const woof = 'woof';
// note below that Diff removes the props from T that exist in WithWoofStringProps
// this leaves us with the props of the originally passed in component (without the injected props)
const hocComponent = (props: Diff<T, WithWoofStringProps>) => (
<WrappedComponent {...(props as T)} woof={woof} />
);
return hocComponent;
}