redux 类型“{}”中缺少属性,但类型...中需要该属性,Typescript连接模式

6tqwzwtp  于 2022-11-12  发布在  TypeScript
关注(0)|答案(2)|浏览(126)

您好,我需要react typescript的连接模式
我有减速器

type State = {
  version: number,
  a?: string 
}

    interface ActionC {
      type: string
      payload?: number 
    }

    type IAction = ActionA | ActionB | ActionC;

    const reducer = (state: State = initialState, action: IAction) => {
      // The reducer normally looks at the action type field to decide what happens
      switch (action.type) {
        // Do something here based on the different types of actions
        default:
          // If this reducer doesn't recognize the action type, or doesn't
          // care about this specific action, return the existing state unchanged
          return state
      }
    }

但是当我使用连接

export const App: FunctionComponent<{ version: number}> = (props) => {

    return (
      <div>APP {props.version}</div>
    )
    }

const mapStateToProps = (state: State) => {
  return {
    version: state.version
  }
};

export default connect(mapStateToProps)(App);

我有错误
类型“{}”中缺少属性“version”,但类型“Omit〈{ version:”中需要该属性数字; },永不〉'. TS 2741
如何解决此问题?

jxct1oxe

jxct1oxe1#

当我从https://redux.js.org/recipes/usage-with-typescript中提取时:
如果你仍然使用connect,你应该使用@types/react-redux^7.1.2导出的ConnectedProps类型来自动推断connect中的属性类型。这需要将connect(mapState,mapDispatch)(MyComponent)调用拆分为两部分:

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

interface RootState {
  isOn: boolean
}

const mapState = (state: RootState) => ({
  isOn: state.isOn
})

const mapDispatch = {
  toggleOn: () => ({ type: 'TOGGLE_IS_ON' })
}

const connector = connect(mapState, mapDispatch)

// The inferred type will look like:
// {isOn: boolean, toggleOn: () => void}
type PropsFromRedux = ConnectedProps<typeof connector>

type Props = PropsFromRedux & {
  backgroundColor: string
}

const MyComponent = (props: Props) => (
  <div style={{ backgroundColor: props.backgroundColor }}>
    <button onClick={props.toggleOn}>
      Toggle is {props.isOn ? 'ON' : 'OFF'}
    </button>
  </div>
)

export default connector(MyComponent)
0md85ypi

0md85ypi2#

函数connect必须有2个参数,而且必须始终有。即使你不使用mapDispatchToProps,你也必须传递它。在JS中可以使用null,而在TS中它应该是一个空对象。所以,你的代码应该是

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

相关问题