mobx-react icon indicating copy to clipboard operation
mobx-react copied to clipboard

[Question] How to get typesafe injection

Open noveyak opened this issue 9 years ago • 83 comments

I've looked at https://github.com/mobxjs/mobx-react#strongly-typing-inject

but am not sure if there is a better way. I generally pick out a lot of things to inject. Imagine

@inject((stores) => {
  return {
    storeA: stores.storeA,
    storeB: stores.storeB,
    storeC: stores.storeC,
    somethingOnStoreD: stores.storeD.something
})
MyComponent extends React.Component<IMyComponentProps>

But if I render this component from a parent component, then I can't render it without marking each one of the stores or props as optional in IMyComponentProps or pass in values for each of those props. This is documented but makes it very difficult to actually use the props in the component.

Basically anytime I use something from storeA, storeB, or somethingOnStoreD - I first have to check for the presence of those or else typescript will complain that it is potentially undefined.

I think part of the problem is typescript currently doesn't allow class mutations from decorators. But even when I use inject as a function, the tsd file specifies inject returns the original target which expects the props declared in IMyComponentProps export function inject<T, P>(storesToProps : IStoresToProps<T, P>): (<TFunction extends IReactComponent<T | P>>(target: TFunction) => (TFunction & IWrappedComponent<T>)); // decorator

If I were to change it the tsd to

export function inject<T, P>(storesToProps : IStoresToProps<T, P>): (<TFunction extends IReactComponent<T | P>>(target: TFunction) => (IReactComponent<P> & IWrappedComponent<T>)); // decorator

and inject with

interface IPropsFromStore {
  storeA: storeA;
  storeB: storeB;
  ...
}
IPropsFromParent {
}
inject<IPropsFromStore, IPropsFromParent>((stores) => {
  return {
    storeA: stores.storeA,
    storeB: stores.storeB,
    storeC: stores.storeC,
    somethingOnStoreD: stores.storeD.something
})(
MyComponent extends React.Component<IPropsFromStore & IPropsFromParent>)

This allows me to use the function to return a component that no longer requires all the props that will be inserted with injection. It also will validate that the inject function is returning the props that I am expecting and also allows MyComponent to use props from injection directly and force checks on props from parent. The problem is this declaration will no longer allow inject to be used as a decorator since its no longer clear that inject returns a signature compatible with the original constructor. I kind of wish this functionality somehow existed because I could be willing to forego decorators to have a better type-checking experience but not sure if its possible.

Sorry this was a bit long, do you know of a better way to solve these problems?

Thanks!

noveyak avatar May 17 '17 06:05 noveyak

Not sure if you're aware, but you can tell TypeScript that you know something is defined by using the following syntax (note the ! on the property access):

const { storeA } = props;
storeA!.something;

See here. Makes this a lot simpler. There is the same problem in a lot of a React libraries that inject props (including redux, react-dnd). It's certainly a TypeScript-specific issue.

jamiewinder avatar May 18 '17 08:05 jamiewinder

The current declaration of React components don't allow this behavior. The only way to properly fix it is to define React.Component with three generic params <PApi, PInside, S>, so that the PApi could define fields as being optional, while PInside is used inside the components, and can mark the same fields as non-optional.

E.g.: MyComponen extends React.Component<{ store?: StoreType }, { store: StoreType }, {}>. That is imho the only proper way to fix this; make a PR on the React component typings. Since in the latest TS versions Generics can have default arguments, this doesn't need to be as breaking as it would have been in the past, if it is possible to express: ReactComponent<P={}, S={}, PInner = P>.

Hope that makes sense. Not much can be done about it from mobx-react side of things.

mweststrate avatar May 25 '17 07:05 mweststrate

Not sure if it's of any help, but I just started picking up MobX and decided to go with a custom inject/observer wrapper to achieve this. The type definitions could arguably be a bit stronger, but for an initial pass it seems to work quite well:

export function connect<MappedProps> (
  mapStoreToProps: (store: Store) => MappedProps
) {
  return function<WrappedProps> (
    WrappedComponent: React.ComponentClass<WrappedProps> | React.StatelessComponent<WrappedProps>,
  ) {
    const ConnectedComponent = inject(mapStoreToProps)(
      observer(WrappedComponent)
    ) as React.ComponentClass<Partial<WrappedProps>>
    return ConnectedComponent
  }
}

// use as:
export default connect((store) => ({
  session: store.session,
}))(MyComponent)

With this, MyComponent does not have to treat the props as if they were optional, and any component rendering the connected (injected) MyComponent does not have to supply any of its props. Clearly what we'd really want is for the connected component to expose only the subset of props that weren't selected via inject, but my limited TypeScript skills have hindered me from accomplishing that thus far.

dvdzkwsk avatar Jun 25 '17 14:06 dvdzkwsk

Any news about this? @amir-arad and I tried a different implementation:

interface MyComponentInternalProps {
    myStore: MyStore;
}

export interface MyComponentExternalProps {
    myStore?: MyStore;
}

export interface MyComponentState {

}

@inject(STORE)
@observer
class MyComponentInternal extends React.Component<MyComponentInternalProps, MyComponentState> {

    render() {
        return (
            <div>
                Hi
            </div>
        );
    }
}

class JSXInterface extends React.Component<MyComponentExternalProps, MyComponentState>{}
export const MyComponent = MyComponentInternal as typeof JSXInterface;

It works, but its messy.

DeDuckProject avatar Jul 04 '17 15:07 DeDuckProject

There is an article on this topic, yet another way to deal with this https://medium.com/@prashaantt/strongly-typing-injected-react-props-635a6828acaf But for me the question is whether it is a good practice to use a bang! operator like this.props.todoStore!.fetchData() or to use the approach from article like this.injected.todoStore.fetchData() Which of these is more readable and maintainable, what do you think guys?

beshanoe avatar Jul 05 '17 09:07 beshanoe

I'd add that the bang nullifies any existing type inference. see: https://github.com/Microsoft/TypeScript/issues/16945

amir-arad avatar Jul 05 '17 11:07 amir-arad

I think the problem is basically that the React typings are too limited. If somebody would be willing to improve the react typings this could be easily addressed. Basically a component needs 3 generic arguments, instead of 2:

React.Component<PropsExternal, PropsInternal, State> where PropsInternal specifies which properties are available inside the component's methods. The PropsExternal would specificy the interface to the outside world.

In that case you could have a component with the following signature: class Component<{ todoStore?: TodoStore }, { todoStore: TodoStore }, {}> { ...}

~Probably the inject signature could even be used to leverage Partials and construct the external properties from the internal ones.~ Nope, type inference starts with the fn, not the components

I am wondering btw whether

export function inject<T, P>(storesToProps : IStoresToProps<T, Partial<P>>): (<TFunction extends IReactComponent<T | P>>(target: TFunction) => (TFunction & IWrappedComponent<T>)); // decorator Could help (adding partial to this def)

mweststrate avatar Jul 06 '17 11:07 mweststrate

I think the root of the problem is in how they implemented JSX support. currently it just uses the props field's type for type checking. we need a marker type like JSXAble<T>, so every class that implements it can be used as JSX with arguments of type T. However I don't know how it will play out with duck-typings. maybe using a hidden symbol field with type T.

anyhow, I have a different approach using this type:

type MyProps<P, T> = {props:Readonly<{ children?: ReactNode }> & Readonly<P>} & T;

so you can use it to cast this for the methods like so:

interface ExtProps{
    store?:{foo:boolean};
}
interface IntProps{
    store:{foo:boolean};
}
class Me extends React.Component<ExtProps>{
    private _:MyProps<IntProps, this> = this as any;
    componentDidUpdate(){
        this._.props.store.foo; // <-- this._.props is of type IntProps so store is not optional
    }
}

I don't like having runtime footprints for type workarounds, but I guess that's a choice.

amir-arad avatar Jul 06 '17 12:07 amir-arad

so there is no workaround for now ?

KatSick avatar Jul 14 '17 12:07 KatSick

work around is marking it optional in props type, and using "!": this.props.store!.invokeAction() or introducing a utility method that returns the non nulled store for internal use

Op vr 14 jul. 2017 om 14:10 schreef Ostap Chervak <[email protected]

:

so there is no workaround for now ?

— You are receiving this because you commented.

Reply to this email directly, view it on GitHub https://github.com/mobxjs/mobx-react/issues/256#issuecomment-315344571, or mute the thread https://github.com/notifications/unsubscribe-auth/ABvGhGDgn9PAdJdvp55pSHcwH8HVX40Uks5sN1q6gaJpZM4NdcXH .

mweststrate avatar Jul 14 '17 14:07 mweststrate

Please everyone running TypeScript >= 2.4.1, try this out :)

import * as React from "react";
import { inject } from "mobx-react";
import { ObjectOmit } from "typelevel-ts"; // Thanks @gcanti, we <3 you all!

declare module "mobx-react" {
  export function inject<D>(
    mapStoreToProps: (store: any) => D
  ): <A extends D>(
    component: React.ComponentType<A>
  ) => React.SFC<ObjectOmit<A, keyof D> & Partial<D>>;
}

const MyComp = ({ label, count }: { label: string; count: number }) =>
  <p>
    {label} x {count} times!
  </p>;
const MyCompConnected = inject((store: any) => ({ count: 1 }))(MyComp);

export const el1 = <MyCompConnected label="hello" />;
export const el2 = <MyCompConnected labels="hello" />; // error! :D
export const el3 = <MyCompConnected label="Hello world!" count={2} />;

Thanks to @gcanti for his help and work who made this possible! ;)

mattiamanzati avatar Jul 14 '17 15:07 mattiamanzati

@mattiamanzati I'll try it out first chance I get

amir-arad avatar Jul 16 '17 07:07 amir-arad

I made this component:

import { inject, IReactComponent } from "mobx-react";

function mobxInject<newProps, oldProps extends newProps>(
  stores: string[],
  wrappedComponent: IReactComponent<oldProps>,
) {
  return inject.apply(null, stores)(wrappedComponent) as IReactComponent<newProps>;
}

export default mobxInject;

...
function CompInternal(props: {store:IStore; passedProps: string}) {
}

const Comp = mobxInject<{passedProps: string}, {store:IStore; passedProps: string}>(["store"], CompInternal);

Bnaya avatar Jul 25 '17 13:07 Bnaya

Also note that an @inject decorator for fields could quite nicely fit the typing problem, like done here: https://github.com/ascoders/dob-react

mweststrate avatar Sep 05 '17 15:09 mweststrate

Same problem with flowtype.

I create my stores as singletons and import them into my components without injecting.

kuuup-at-work avatar Sep 12 '17 13:09 kuuup-at-work

Can we do something like in the react-redux type definition by explicitly defining the types of InjectedProps and OwnProps?

zhahaoyu avatar Sep 18 '17 03:09 zhahaoyu

The following type definition makes more sense to me, but somehow this fails to be used as a decorator. Reasons:

  1. The wrapped component should accept both the injected props T as well as props P passed by parent, therefore I changed | to &
  2. The new component generated from the HOC should only expose the props P, and T is no longer visible to the outside because they have been injected by the mapper function, so instead of using TFunction, we use TNewFunction
export function inject<T, P>(storesToProps: IStoresToProps<T, P>): <TFunction extends IReactComponent<T & P>, TNewFunction extends IReactComponent<P>>(
  target: TFunction
) => TNewFunction & IWrappedComponent<P>;

I made the following simple wrapper of inject which seems to do the work.

export function mobxInject<T, P>(storesToProps: IStoresToProps<T, P>): (
  <TFunction extends IReactComponent<T & P>, TNewFunction extends IReactComponent<P>>(
    target: TFunction
  ) => TNewFunction & IWrappedComponent<P>
) {
  return inject(storesToProps) as 
    <TFunction extends IReactComponent<T & P>, TNewFunction extends IReactComponent<P>>(
      target: TFunction
    ) => TNewFunction & IWrappedComponent<P>;
}

zhahaoyu avatar Sep 18 '17 04:09 zhahaoyu

@mattiamanzati any idea how to convert your definition to work as decorator? Thank you!

RafalFilipek avatar Sep 26 '17 09:09 RafalFilipek

@RafalFilipek In TypeScript decorators can't change class type definition, so that is impossible unfortunately :)

mattiamanzati avatar Sep 26 '17 09:09 mattiamanzati

Hi, I do not understand why you return:

export function inject<T, P>(
    storesToProps: IStoresToProps<T, P>
): (<TFunction extends IReactComponent<T | P>>(
    target: TFunction
) => TFunction & IWrappedComponent<P>) // WHY TFunction?

What makes more sense to me is:

export function inject<T, P>(
    storesToProps: IStoresToProps<T, P>
): (<TFunction extends IReactComponent<T | P>>(
    target: TFunction
) => IReactComponent<P>) // only the container props will be required !!

The problem is that if component has compulsory paramaters which are fulfiled by container, using your definition also the container will have those compulsory parameters which is incorrect.

The problem of my "fix" is that it does not work with decorator.

So, what is the reasoning for returning also the component parameters? And can I somehow fix that to work with decorators? Thanks

tomitrescak avatar Oct 05 '17 21:10 tomitrescak