Skip to content

Commit 2d0a8f4

Browse files
authored
Merge pull request #73 from sw-yx/hoc-update
Update HOC section
2 parents 0ce51d2 + a3ba8c1 commit 2d0a8f4

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

ADVANCED.md

+17-2
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ The following utilities will be needed.
104104
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
105105

106106
/**
107-
* Mark mark all the properies from K in T as optional.
107+
* Remove from T the keys that are in common with K
108108
*/
109109
type Optionalize<T extends K, K> = Omit<T, keyof K>;
110110
```
@@ -125,12 +125,27 @@ export function withTheme<T extends WithThemeProps = WithThemeProps>(WrappedComp
125125
const themeProps = getThemePropsFromSomeWhere();
126126

127127
// this.props comes afterwards so the can override the default ones.
128-
return <WrappedComponent {...themeProps} {...this.props} />;
128+
return <WrappedComponent {...themeProps} {...this.props as T} />;
129129
}
130130
}
131131
}
132132
```
133133

134+
Note that the `{...this.props as T}` assertion is needed because of a current bug in TS 3.2 https://github.com/Microsoft/TypeScript/issues/28938#issuecomment-450636046
135+
136+
Here is a more advanced example of a dynamic higher order component that bases some of its parameters on the props of the component being passed in:
137+
```ts
138+
// inject static values to a component so that they're always provided
139+
export function inject<TProps, TInjectedKeys extends keyof TProps>(
140+
Component: React.JSXElementConstructor<TProps>,
141+
injector: Pick<TProps, TInjectedKeys>
142+
) {
143+
return function Injected(props: Omit<TProps, TInjectedKeys>) {
144+
return <Component {...props as TProps} {...injector} />
145+
}
146+
}
147+
```
148+
134149
## Render Props
135150

136151
Sometimes you will want to write a function that can take a React element or a string or something else as a prop. The best Type to use for such a situation is `React.ReactNode` which fits anywhere a normal, well, React Node would fit:

0 commit comments

Comments
 (0)