提问者:小点点

Typescript React/Redux:类型为“typeof MyClass”的参数不能分配给类型为“ComponentType<…”的参数


我是Redux的新手,也是TypeScript的新手。

我已经找到了一个相当好的基本的缩减版本,我试图在反应还原文档中做什么。

代码是这样的:

import * as actionCreators from '../actions/index'
import { bindActionCreators } from 'redux'
import React, { Component } from 'react'
import { connect } from 'react-redux'

class TodoApp extends Component {
    render() {
        return (<div>test!</div>)
    }
}
function mapStateToProps(state) {
  return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
  return { actions: bindActionCreators(actionCreators, dispatch) }
}


export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)

我的代码编辑器(带有TSLint扩展的VS Code)和tsc都将最终的(TodoApp)突出显示为错误,这是我得到的消息:

src/组件/测试。tsx(20,61):错误TS2345:类型为“typeof TodoApp”的参数不能分配给类型为“ComponentType”的参数

20导出默认连接(mapStateToProps, mapDispatchToProps)(TodoApp)

我的问题是,我不完全理解mapStateToProps和连接在做什么,但是在理解之前,我想知道是否有代码更改,我可以在这里修复这个打字错误...


共2个答案

匿名用户

您的react组件不需要道具,因此您的connect有一个错误,因为它推断MapStateTropsmapDispatchToProps都应该返回空对象

您可以通过为反应道具添加类型def来解决这个问题,但是也有很多不安全的隐式any的使用。如果为了安全起见而完全键入这个应用程序,它看起来会像这样......

interface ITodo {
  description: string
}

interface ITodosState {
  todos: ITodo[]
}

interface ITodoProps {
  todos: ITodo[]
}

interface ITodoActionProps {
  someAction: () => void
}

class TodoApp extends React.Component<ITodoProps & ITodoActionProps> {
    render() {
        return (<div>test!</div>)
    }
}

function mapStateToProps(state: ITodosState): ITodoProps {
  return { todos: state.todos }
}

function mapDispatchToProps(dispatch: Dispatch<ITodosState>): ITodoActionProps {
  return bindActionCreators({ someAction: actionCreators.someAction }, dispatch)
}

export default connect<ITodoProps, ITodoActionProps, {}>(mapStateToProps, mapDispatchToProps)(TodoApp)

匿名用户

你还没有输入TodoApp的道具。

type Props = {
    todos: any[] // What ever the type of state.todos is
    actions: {
       addTodo: Dispatch<any>
    }
}

class TodoApp extends React.Component<Props> {
    render() {
        return <div>test!</div>
  }
}