Skip to content

Commit d51511c

Browse files
author
sw-yx
committed
fix HOC example
1 parent 2aec7a4 commit d51511c

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

HOC.md

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -206,11 +206,6 @@ Here we build our own mini `connect` to understand HOCs:
206206
```tsx
207207
/** utility types we use */
208208
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
209-
type Optionalize<T extends K, K> = Omit<T, keyof K>;
210-
// // ACTUAL HOC
211-
interface WithSubscriptionProps {
212-
data: TODO_ANY;
213-
}
214209

215210
/** dummy Data */
216211
type CommentType = { text: string; id: number };
@@ -226,9 +221,8 @@ const comments: CommentType[] = [
226221
];
227222
/** dummy child components that take anything */
228223
const Comment = (_: any) => null;
229-
type TODO_ANY = any;
230224
/** Rewritten Components from the React docs that just uses injected data prop */
231-
function CommentList({ data }: WithSubscriptionProps) {
225+
function CommentList({ data }: WithSubscriptionProps<typeof comments>) {
232226
return (
233227
<div>
234228
{data.map((comment: CommentType) => (
@@ -254,22 +248,25 @@ const ConnectedComment = connect(
254248
commentActions
255249
)(CommentList);
256250

251+
// these are the props to be injected by the HOC
252+
interface WithSubscriptionProps<T> {
253+
data: T;
254+
}
257255
function connect(mapStateToProps: Function, mapDispatchToProps: Function) {
258-
return function<T extends WithSubscriptionProps = WithSubscriptionProps>(
256+
return function<T, P extends WithSubscriptionProps<T>, C>(
259257
WrappedComponent: React.ComponentType<T>
260258
) {
259+
type Props = JSX.LibraryManagedAttributes<C, Omit<P, 'data'>>;
261260
// Creating the inner component. The calculated Props type here is the where the magic happens.
262-
return class ComponentWithTheme extends React.Component<
263-
Optionalize<T, WithSubscriptionProps>
264-
> {
261+
return class ComponentWithTheme extends React.Component<Props> {
265262
public render() {
266263
// Fetch the props you want inject. This could be done with context instead.
267264
const mappedStateProps = mapStateToProps(this.state, this.props);
268265
const mappedDispatchProps = mapDispatchToProps(this.state, this.props);
269266
// this.props comes afterwards so the can override the default ones.
270267
return (
271268
<WrappedComponent
272-
{...this.props as T}
269+
{...this.props}
273270
{...mappedStateProps}
274271
{...mappedDispatchProps}
275272
/>

0 commit comments

Comments
 (0)