【问题标题】:How to properly use react-redux connect with typescript@3?如何正确使用 react-redux 与 typescript@3 连接?
【发布时间】:2019-03-27 10:39:44
【问题描述】:

我正在尝试使用 TypeScript 和 react-redux 创建类型安全的 HOC。

hoc/with-is-visible-range.tsx

import React from "react";
import { Subtract } from "utility-types";
import { connect } from "react-redux";
import { rangeVisibilitySelector } from "./date-range.selectors";

interface IInjectedProps {
  visible: boolean;
}

interface IMappedProps {
  isVisible: boolean;
}

const withIsVisibleRange = <T extends IInjectedProps>(
  Component: React.ComponentType<T>
) => {
  const WrappedComponent: React.SFC<
    Subtract<T, IInjectedProps> & IMappedProps
  > = ({ isVisible, ...rest }: IMappedProps) => {
    return <Component {...rest} visible={isVisible} />;
  };

  const mapStateToProps = (state: ApplicationState) => ({
    isVisible: rangeVisibilitySelector(state)
  });

  return connect(
    mapStateToProps,
    null
  )(WrappedComponent);
};

export default withIsVisibleRange;

但我总是遇到同样的错误:

错误信息:

错误:(30, 5) TS2345: 'StatelessComponent> & IMappedProps>' 类型的参数不可分配给'ComponentType> & IMappedProps>>' 类型的参数。类型 'StatelessComponent> & IMappedProps>' 不可分配给类型 'StatelessComponent> & IMappedProps>>'。类型 'Pick> & IMappedProps' 不可分配给类型 'Matching & IMappedProps>'。类型 '(Pick> & IMappedProps)[P]' 不能分配给类型 'P extends "isVisible" ? ({ isVisible: boolean; } & null)[P] 扩展 (Pick> & IMappedProps)[P] ? (Pick> & IMappedProps)[P] : ({ ...; } & null)[P] : (Pick<...> & IMappedProps)[P]'。

【问题讨论】:

    标签: reactjs typescript redux react-redux


    【解决方案1】:

    虽然在@types/react-redux 中的connect 声明中使用的类型操作(Matching 等)适用于任何给定 props 类型,但 TypeScript 编译器无法象征性地推理当它们应用于涉及类型参数T 的道具类型时会发生什么。不幸的是,您必须使用类型断言,即WrappedComponent as any

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 1970-01-01
      • 2018-03-10
      • 2018-06-25
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2022-07-06
      • 2019-06-06
      相关资源
      最近更新 更多