首页 > 解决方案 > 在 Typescript 中使用 React Props 的传播运算符(错误:...可以用不同的约束子类型 {} 实例化)

问题描述

我正在尝试使用接收道具的 Typescript 在 React 中编写一个高阶组件,“消耗”其中一个,然后将其余部分传递给子组件。

function testConnect<T>(Child: React.ComponentType<T>): React.ComponentType<T> {

  type InitialState = {
    iS: StoreShape.State;
  };

  type LAP = InitialState & T;

  const Connector = (props: LAP) => {
    const { iS, ...rest } = props;
    // do something with iS
    return (
      <Child // Visual Studio complains about this line.
        {...rest}
      />
    );
  };

  return Connector;
}

但是,这失败并出现错误:'Pick<LAP, Exclude<keyof T, "iS">>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'

我不仅想知道我是否能做些什么,而且还想知道为什么会发生这种情况。

标签: javascriptreactjstypescript

解决方案


实际上,Typescript 遇到了您的组件的问题:

 const Component = testConnect(({ iS }) => <div>{iS}</div>);

 <Component iS={...} />

所以你要么必须

(a) 将所有道具(而不仅仅是休息)传递给组件。

   <Child   {...props} />

iS(b) 通过从 T中排除键,确保不能传入名为“iS”的任何道具:

 testConnect<T>(Child: React.ComponentType<Omit<T, "iS">>>): React.ComponentType<T> {

推荐阅读