2

Using TypeScript and React/Redux, I have typed a ConnectedComponent. But when I try to render that component, TypeScript is throwing an error saying that the required props aren't passed.

Ex.

interface Props extends MapStateProps {

}

class App extends React.Component<Props, {}> {
  render(): JSX.Element {
    return (
      <>
        <Router>
          <Switch>
            <Route path="/" component={Dashboard} />
          </Switch>
        </Router>
      </>
    );
  }
}

interface MapStateProps {
  user: UserState;
}

const MapStateToProps = (state: AppState): MapStateProps => ({
  user: state.user,
});

const connectedApp = connect(MapStateToProps, null)(App);

export {
  connectedApp as App,
};

Then when I render the component like:

<App />

It says that App requires the 'user' prop. How can I do this without setting the user prop as optional?

3 Answers 3

1

Please try this and see if it helps.

interface UserState{}
interface AppState{
  user: UserState;
}
interface MapStateProps {
  user: UserState;
}
interface Props extends MapStateProps {}

class App2 extends React.Component<Props, {}> {
  render(): JSX.Element {
    return (
      <div>
          App2
      </div>
    );
  }
}

const MapStateToProps = (state: AppState): MapStateProps => ({
  user: state.user,
});

export default connect(MapStateToProps, null)(App2);

Sign up to request clarification or add additional context in comments.

2 Comments

I tried that as well, but can never get that to work. It always says that mapStateToProps doesn't satisfy StateProps.
@hairyhendrix I have modified code and this one was working for me. It seems your MapStateProps interface and AppState interface user type is different in both.
0

Replacing

export {
  connectedApp as App,
};

With the default export:

export default connectedApp;

And then the import

import {App} from './App';

For

import App from './App';

1 Comment

I tried that before, and again now, and unfortunately it has the same effect.
0

Here is what worked for me:

//...

const connectedApp = connect(MapStateToProps, null)(App);

export default connectedApp ;
export { connectedApp as App};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.