mobxjs / mobx-react

React bindings for MobX
https://mobx.js.org/react-integration.html
MIT License
4.85k stars 349 forks source link

How to declare mobx prop types using typescript, react and mobx #841

Closed serendipity1004 closed 4 years ago

serendipity1004 commented 4 years ago

I have a functional root component like below

const RootPage: React.FC = () => {
    const classes = useStyles();

    return (
        <React.Fragment>
            <Sidebar/>
            <Grid container className={classes.fullHeight}>
                <Map/>
            </Grid>
        </React.Fragment>
    )
};

and my map component is looking like below

interface IMapProps {
    map:MapStore;
}

const Map : React.FC<IMapProps> = (props)=>{
    return (
        <div>
            {props.map}
        </div>
    )
};

export default (inject('map'))(observer(Map));

I am expecting IMapProps to obviously come from the mobx injection; however, typescript is throwing error saying that I should provide the props in the root component. Error looks like below

react_front_1    | Property 'map' is missing in type '{}' but required in type 'IMapProps'.  TS2741
react_front_1    | 
react_front_1    |     22 |             <Sidebar/>
react_front_1    |     23 |             <Grid container className={classes.fullHeight}>
react_front_1    |   > 24 |                 <Map/>
react_front_1    |        |                  ^
react_front_1    |     25 |             </Grid>
react_front_1    |     26 |         </React.Fragment>
react_front_1    |     27 |     )

How do I provide types for props that come from the mobx store?

danielkcz commented 4 years ago

If you search through issues here, you will find some solutions around typing inject correctly.

However, you might consider abandoning inject if you want to save yourself some soul health :)

mweststrate commented 4 years ago

See #256: You will have the make map optional, map?: MapStore, and at non-null assertions inside your component if needed; {props.map!}.

useContext is an easier way to get type-safe injection in FC's, so we recommend to use that now.

danielkcz commented 4 years ago

@serendipity1004 I am sorry if my response sounded a bit harsh, that wasn't the intention. As the link states, there is nothing wrong about inject and you can keep using it, but be prepared for some extra battles that can be solved more easily with Context.

lock[bot] commented 4 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs or questions.