Last active
July 24, 2019 21:31
-
-
Save shilangyu/264a604443e922ba9972f31fd985a7cb to your computer and use it in GitHub Desktop.
Strongly typed Mobx-React `inject` that separates injects from props
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { inject, IStoresToProps } from 'mobx-react' | |
import { Component } from 'react' | |
import UserStore from './UserStore' // import your stores | |
import AuthStore from './AuthStore' // import your stores | |
export const user = new UserStore() | |
export const auth = new AuthStore() | |
export interface IStores { | |
user: UserStore, | |
auth: AuthStore | |
} | |
export class ConnectedComponent<P, I, S = {}> extends Component<P, S> { | |
public get injects() { | |
return (this.props as any) as I | |
} | |
} | |
export function connect(...storeNames: Array<keyof IStores>): ReturnType<typeof inject> | |
export function connect<P, C, I>( | |
mapStoresToInjects: IStoresToProps<IStores, P, C, I>, | |
): ReturnType<typeof inject> | |
export function connect(): ReturnType<typeof inject> { | |
return inject(...arguments) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now instead of extending
React.Component
, extend theConnectedComponent
which takes one extra generic of injects interface. Now you can use a strongly typedconnect
(our new inject) and access the injected values inthis.injects
(no more optional props in interface definition). see more here