结合使用HOC和redux时如何正确键入组件道具

时间:2020-06-25 14:35:01

标签: reactjs typescript redux

我从此处遵循官方指南:https://react-redux.js.org/using-react-redux/static-typing,但它似乎对我不起作用。 这是SSCCE。以下代码无法通过以下方式进行静态类型检查:

TS2339: Property 'a' does not exist on type 'never'.

我正在使用"react-redux": "^7.2.0""@types/react-redux": "^7.1.9"。代码是:

import React, {FunctionComponent} from 'react';

import { connect, ConnectedProps } from 'react-redux';

type RootState = {a: number};

const mapStateToProps = (state: RootState) => {
    return {a: state.a};
};

const connector = connect(mapStateToProps, null);
type PropsFromRedux = ConnectedProps<typeof connector>


const MyComponent: FunctionComponent<PropsFromRedux> = (props: PropsFromRedux) => {
  return <span>{props.a}</span>;
};

export default connector(MyComponent);

使用类组件,如:

class MyComponent extends React.Component<PropsFromRedux> {

  constructor(props: PropsFromRedux) {
    super(props);
  }

  render() {
    return <span>{this.props.a}</span>;
  }
}

...产生完全相同的消息。

0 个答案:

没有答案