Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux, React, Typescript: Connect returns view class which requires props

I have the following example:

import * as React from "react";
import { connect } from 'react-redux';


interface IMessage {
    message : string;
}

class SayMessage extends React.Component<IMessage, {}>{
    render () {
        return (<div>{this.props.message}</div>);
    }
}


function mapStateToProps( state : any ) : IMessage {
  return { message : "Hello, world" };
}
const SayMessageContainer = connect(mapStateToProps)(SayMessage);

export class SomeOtherView extends React.Component<{},{}>{
    render (){
        return (<SayMessageContainer/>);
    }
}

Which throws on <SayMessageContainer/>:

Property 'message' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes & IMessage & { children?: ReactElement...'.

How should this example be changed so that Connect can provide the props through mapStateToProps?

Note / possible hint: SayMessageContainer is typeof SayMessage, which seems off to me.

Typescript 2.0.0

Edit

Writing my own container seems to solve it, but I'd rather figure out how to do it properly using connect

class SayMessageContainer extends React.Component<{},{}>{
    render () {
        const props = mapStateToProps({});
        return (
            <SayMessage {...props}/>
        );
    }
}

Edit 2 Using the following typings:

"react-redux": "registry:npm/react-redux#4.4.0+20160614222153", 
"react-router": "registry:npm/react-router#2.4.0+20160628165748", 
"react-router-redux": "registry:npm/react-router-redux#4.0.0+20160602212457",
"redux": "registry:npm/redux#3.0.6+20160214194820"
like image 779
Andrew Carreiro Avatar asked May 18 '26 02:05

Andrew Carreiro


1 Answers

You have to create an interface for each type of props and then pass it to the connect method :

// Regular props
interface OwnProps {}

// Props from the mapStateToProps method
interface StateProps {
    message: string;
}

// Props from the mapDispatchToProps method
interface DispatchProps {}

To create your component, you can use a specific type :

type SayMessageProps = OwnProps & StateProps & DispatchProps;

class SayMessage extends React.Component<SayMessageProps, {}>{
    render () {
        return (<div>{this.props.message}</div>);
    }
}

Then when using connect :

connect<StateProps, DispatchProps, OwnProps>(mapStateToProps)(SayMessage);

(you can also use {} instead of empty interfaces)

like image 119
Bouni Avatar answered May 19 '26 16:05

Bouni