如何正确使用带有typescript @ 3的react-redux连接?

时间:2018-10-23 08:48:27

标签: reactjs typescript redux react-redux

我正在尝试使用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 <{isVisible:boolean; }和null,选择>&IMappedProps>'。类型'(Pick>&IMappedProps)[P]'是否可分配给类型'P扩展“ isVisible”? ({isVisible:boolean;}&null)[P]扩展(Pick>&IMappedProps)[P]吗? (Pick>和IMappedProps)[P]:({...;}和null)[P]:(Pick <...>和IMappedProps)[P]'。

1 个答案:

答案 0 :(得分:0)

Matching的{​​{1}}声明中使用的类型操作(connect等)适用于任何 gift 道具类型,TypeScript编译器无法将它们应用到涉及类型参数@types/react-redux的道具类型时发生象征性的推理。不幸的是,您必须使用类型断言,即T