【问题标题】:Why is typescript triggering an error in my HOC that uses rest props when I try to pass another prop?当我尝试传递另一个道具时,为什么打字稿会在我的使用休息道具的 HOC 中触发错误?
【发布时间】:2019-06-13 11:44:05
【问题描述】:

我编写了一个包装器,通过注入 store prop 将组件连接到 store。包装器代码工作正常并通过测试。

import React, { ComponentType } from 'react';
import store from './index';
import { RootStore } from './RootStore';

interface InjectedStoreProps {
  store: RootStore;
}

const withStore = (WrappedComponent: ComponentType<InjectedStoreProps>) => {
  const output = ({...props}) => <WrappedComponent store={store} {...props} />;
  return output;
}

export default withStore;

但是,在我的一项测试中,我有

const ComponentToWrap = withStore(
  ({store, otherProp}) => (
    <div>
      <span>
        {store}
      </span>
      <span>
        {otherProp}
      </span>
    </div>
  )
);

导致打字稿错误Type 'PropsWithChildren&lt;InjectedStoreProps&gt;' has no property 'otherProp' and no string index signature.

我是打字稿的新手,所以肯定会误解一些东西。我尝试了许多谷歌搜索的东西,但没有一个有帮助。

反应 v16.8.6 打字稿 v3.4.3

【问题讨论】:

    标签: reactjs typescript higher-order-functions


    【解决方案1】:

    问题是您试图解构 (https://basarat.gitbooks.io/typescript/docs/destructuring.html) 一个没有属性 otherProp 的对象。你可以通过添加来解决这个问题:

    interface InjectedStoreProps {
      store: RootStore;
      otherProp: any;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 2021-03-17
      • 2019-09-25
      • 2019-10-06
      • 2022-12-17
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多