将Typescript与React-Redux一起使用时出现类型错误
我正在尝试将React-redux与Typescript一起使用,当我尝试使用connect()和mapStateToProps注入道具时遇到类型错误。
我的组件如下所示:
function mapStateToProps(state) {    return {
        counter: state.counter
    };
}
function mapDispatchToProps(dispatch) {
    return {
        incr: () => {
            dispatch({type: 'INCR', by: 2});
        },
        decr: () => {
            dispatch({type: 'INCR', by: -1});
        }
    };
}
export default class Counter extends React.Component<HelloProps, any> {
    render() {
        return (
          <div>
              <p>
                  <label>Counter: </label>
                  <b>#{this.props.counter}</b>
              </p>
              <button onClick={e => this.props.incr() }>INCREMENT</button>
              <span style={{ padding: "0 5px" }}/>
              <button onClick={e => this.props.decr() }>DECREMENT</button>
        );
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
商店看起来像这样
let store = createStore(    (state:HelloState, action:HelloAction) => {
        switch (action.type) {
            case 'INCR':
                return {counter: state.counter + action.by};
            default:
                return state;
        }
    },
最后,我将类型定义为:
interface HelloProps {    counter?: number;
    incr?: () => any;
    decr?: () => any;
}
interface HelloState { 
    counter:number;
}
interface HelloAction { 
    type:string, 
    by:number;
}
当我尝试编译代码时,出现以下错误:
(39,61): error TS2345: Argument of type 'typeof Counter' is not assignable to parameter of type 'ComponentClass<{ counter: any; } & { incr: () => void; decr: () => void; }> | StatelessComponent<...'.  Type 'typeof Counter' is not assignable to type 'StatelessComponent<{ counter: any; } & { incr: () => void; decr: () => void; }>'.
    Type 'typeof Counter' provides no match for the signature '(props?: { counter: any; } & { incr: () => void; decr: () => void; }, context?: any): ReactElement<any>'
有趣的是,即使代码抛出类型错误,它仍然可以正常工作。同样,将组件的prop接口更改为any也可以解决该问题。似乎类型系统无法理解这两个映射功能将两个对象合并在一起。
回答:
我在有关Github
问题的倒数第二篇文章中找到了答案。如果mapStateToPropsand和/或mapDispatchToPropsor
上都没有type参数,connect则会产生两个map函数的返回类型的交集。
以上是 将Typescript与React-Redux一起使用时出现类型错误 的全部内容, 来源链接: utcz.com/qa/401151.html

