将带有任意/通用道具的组件传递给 TypeScript 中的 react-redux 连接函数

Nat*_*ema 7 typescript react-redux

我正在尝试将react-redux具有任意/通用道具的 React 元素连接起来,但它没有正确编译。我已经尝试使用JSXElementConstructorand(new (props: Props) => React.Component<Props, any>)而不是ComponentType,但是关于如何Props使用不同的类型实例化出现了不同的错误。这是代码。任何帮助,将不胜感激。

https://github.com/piotrwitek/react-redux-typescript-guide/issues/55看起来相关,但这似乎是关于具有通用的道具,而不是道具本身是通用的。

代码

import React from "react";
import { connect } from "react-redux";

interface StoreState {
  someState: number;
}

// Tried `React.JSXElementConstructor<Pros>`
// and `(new (props: Props) => React.Component<Props, any>)`
// instead of `React.ComponentType<Props>`, but got a different error.
function createWrapperComponent<Props>(
  componentElement: React.ReactElement<
    Props,
    React.ComponentType<Props> & { update(props: Props): void }
  >
) {
  const props = componentElement.props;
  const UnconnectedComponent = componentElement.type;
  const ConnectedComponent = connect<StoreState, {}, Props, StoreState>(
    (state) => state
  )(UnconnectedComponent);

  return class WrapperComponent extends React.Component<any> {
    static update = UnconnectedComponent.update;
    render() {
      return <ConnectedComponent {...props} />;
    }
  };
}

Run Code Online (Sandbox Code Playgroud)

游乐场链接: 提供

J. *_*ema 2

更新:这是一种避免初始转换为any. 现在我正在铸造传递给的道具ConnectedComponent。调查那里的类型问题可能会揭示是否存在比我提到的更多的潜在问题。


你所做的事情并不健全。如果Props{ someState: string },你UnconnectedComponent会期望它的someStateprop 是 a string,但它会是 a number

如果statePropsdispatchProps应该 override ownProps,这就是您的代码现在正在做的事情,我不确定您是否能够让类型按照您想要的方式自动工作。TypeScript 无法判断以下内容是否正确:

function a<Props>(
  b: { [K in keyof Props]: K extends keyof StoreState ? StoreState[K] : Props[K] }
): Omit<Props, keyof StoreState>
{
  return b;
}

Run Code Online (Sandbox Code Playgroud)

也许你应该硬着头皮使用any以下是如何尝试使面向调用者的类型更安全的示例。

如果您想ownProps重写stateProps,则需要向 提供一个mergeProps参数connect

但是,请注意,当您创建ReactElementvia JSX 时,该type字段的类型为any,如果您随后调用 ,这当然不会为您提供类型安全createComponent