如何使用打字稿,React和Mobx声明Mobx道具类型

时间:2020-02-19 03:33:09

标签: reactjs typescript mobx

我有一个像下面这样的功能性根组件

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

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

我的地图组件如下所示

interface IMapProps {
    map:MapStore;
}

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

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

我希望IMapProps显然来自mobx注入;但是,打字稿抛出错误,说我应该在根组件中提供道具。错误如下所示

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 |     )

如何为来自mobx商店的道具提供类型?

1 个答案:

答案 0 :(得分:0)

您需要将它们标记为可选道具。

interface IMapProps {
    map?: MapStore;
}

尽管在那之后您可能需要使用非null断言,例如,如果您的tsconfig设置为strict,则像props.map!

现在更好的方法是使用React.createContext并进行自定义钩子以获取商店

const store = useStore()

这样,您甚至不需要描述道具界面,因为您的商店将来自此钩子。

更多信息在这里: https://mobx-react.js.org/recipes-context