Shawn
Shawn

Reputation: 2435

Rendering react component using typescript without passing in strongly typed props

I am having an issue trying to stronly type the props of a react component and only passing in 1 property to that component.

So take this for example:

I have this class App and it has a child component of class SideMenu. SideMenu has strongly type props like so:

class SideMenu extends Component<ISideMenu> {
    render() {
        return (
            <div>
                Test
            </div>
        );
    }
}

const mapStateToProps = (state: IFileExplorerState) => {
    return {
        fileExplorerInfo: state.fileExplorer
    };
};

export default connect<{}, {}, ISideMenu, IFileExplorerState>(mapStateToProps, {})(SideMenu);

and this is the ISideMenu interface I am using to strongly type the props:

export interface ISideMenu {
    fileExplorerInfo: IFileExplorerState;
}

So now in my App class I am trying to render the SideMenu component, but typescript displays an error saying that I am not passing the prop fileExplorerInfo into that component. I would prefer not to have to do this due to redux populating that prop for me to use from the store's state. Does anybody have a recommendation on how I can handle this better?

class App extends Component {
    render() {
        return (
            <div>
                <SideMenu />
            </div>
        );
    }
}

Upvotes: 1

Views: 692

Answers (1)

You missed the order of the types in connect function

connect<TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = {}>
  • TStateProps comes from state in mapStateToProps
  • TOwnProps comes from outside

You should use connect like this:

export default connect<ISideMenu, {}, {}, IFileExplorerState>(mapStateToProps, {})(SideMenu);

Or you can leave empty the "generic part"

export default connect(mapStateToProps, {})(SideMenu);

Upvotes: 1

Related Questions