@@ -206,11 +206,6 @@ Here we build our own mini `connect` to understand HOCs:
206
206
``` tsx
207
207
/** utility types we use */
208
208
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
- }
214
209
215
210
/** dummy Data */
216
211
type CommentType = { text: string ; id: number };
@@ -226,9 +221,8 @@ const comments: CommentType[] = [
226
221
];
227
222
/** dummy child components that take anything */
228
223
const Comment = (_ : any ) => null ;
229
- type TODO_ANY = any ;
230
224
/** Rewritten Components from the React docs that just uses injected data prop */
231
- function CommentList({ data }: WithSubscriptionProps ) {
225
+ function CommentList({ data }: WithSubscriptionProps < typeof comments > ) {
232
226
return (
233
227
<div >
234
228
{ data .map ((comment : CommentType ) => (
@@ -254,22 +248,25 @@ const ConnectedComment = connect(
254
248
commentActions
255
249
)(CommentList );
256
250
251
+ // these are the props to be injected by the HOC
252
+ interface WithSubscriptionProps <T > {
253
+ data: T ;
254
+ }
257
255
function connect(mapStateToProps : Function , mapDispatchToProps : Function ) {
258
- return function <T extends WithSubscriptionProps = WithSubscriptionProps >(
256
+ return function <T , P extends WithSubscriptionProps < T >, C >(
259
257
WrappedComponent : React .ComponentType <T >
260
258
) {
259
+ type Props = JSX .LibraryManagedAttributes <C , Omit <P , ' data' >>;
261
260
// 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 > {
265
262
public render() {
266
263
// Fetch the props you want inject. This could be done with context instead.
267
264
const mappedStateProps = mapStateToProps (this .state , this .props );
268
265
const mappedDispatchProps = mapDispatchToProps (this .state , this .props );
269
266
// this.props comes afterwards so the can override the default ones.
270
267
return (
271
268
<WrappedComponent
272
- { ... this .props as T }
269
+ { ... this .props }
273
270
{ ... mappedStateProps }
274
271
{ ... mappedDispatchProps }
275
272
/>
0 commit comments