typescript、react-redux中如何编写props

typescript、react-redux中如何编写props

相关代码

// actions.ts
import { Dispatch } from "redux";
import { connect } from "http2";

const getUserInfo = (name: string) => (dispatch: Dispatch) => {
  return Promise.resolve('Hello ' + name) // 也可请求数据并dispatch({ type: xx, payload: xx })
}

// User.tsx
interface IUserProps extends ReturnType<typeof mapStateToProps>, ReturnType<typeof mapDispatchToProps>
const User = (props: IUserProps) => {
  React.useEffect(() => {
    props.getUserInfo('Hello')
  }, [])
  return (<div>xxx</div>)
}

const mapStateToProps = () => {
  return {}
}

const mapDispatchToProps = {
  getUserInfo
}
export default connect(mapStateToProps, mapDispatchToProps)(User)

tslint报错:
Type '{ getUserInfo: (name: string) => (dispatch: Dispatch<AnyAction>) => Promise<unknown>; }' does not satisfy the constraint '(...args: any) => any'

如何能去掉报错,且在编辑时 User 中较好的提示 props.getUserInfo 的参数类型

阅读 2.9k
2 个回答

自问自答来一波:

type BoundThunk<T extends (...args: any[]) => ThunkAction<any, any, any, any>> =
  (...args: Parameters<T>) => ReturnType<ReturnType<T>>;

type StateProps = ReturnType<typeof mapStateToProps>
type DispatchProps = { [P in keyof typeof mapDispatchToProps]: BoundThunk<typeof mapDispatchToProps[P]> }
type OwnProps = {}
type Props = StateProps & DispatchProps & OwnProps

这样,在 User 中,调用 mapStateToProps 或者 mapDispatchToProps 注入的属性、方法都会很好的提示作用

clipboard.png

真是麻烦:ReturnType<typeof mapDispatchToProps> 改为 typeof mapDispatchToProps 就啥事都没了。

而且 const mapDispatchToProps = {}; 这种写法,connect会自动帮你补上dispatch的,不需要再处理dispatch

const action = (id: number) => {
  return {
    type: 'fetch',
    uri: '...',
  };
};

// 这样就行了,已经有dispatch了
const mapDispatchToProps = {
  myAction: action,
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进