1

我用 HOC 包装我的组件的导出,向它添加了 prop,但是 TypeScript 没有看到 HOC 已经添加了这个 prop(这是必需的)。

零件:

import * as React from "react";
import { withText } from "../hoc";

interface Props {
  text: string;
}

function TestComponent({ text }: Props) {
  return <div>{text}</div>;
}

export default withText(TestComponent);

特设:

import * as React from "react";
import { useContext, ReactElement, ComponentType } from "react";
import { TextContext } from "../contexts";

const withText = <P extends object>(
  Component: ComponentType<P>
): ((props: P) => ReactElement) => props => (
  <Component text={useContext(TextContext).value} {...props} />
);

export default withText;

语境:

import { createContext } from "react";

const TextContext = createContext<{ value: string }>({
  value: ""
});

export default TextContext;

应用程序:

import * as React from "react";
import { render } from "react-dom";
import { TextContext } from "./contexts";
import { TestComponent } from "./components";

function App() {
  return (
    <TextContext.Provider value={{ value: "Lorem ipsum" }}>
      <TestComponent /> /* TS throws an error here */
    </TextContext.Provider>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

引发 TS 的错误: Property 'text' is missing in type '{}' but required in type 'Props'

预期行为:TypeScript 知道 withText HOC 已经添加了 'text' 属性

链接到代码框 ->这里

4

1 回答 1

1

这应该适合你

 type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
 interface InterfaceToOmit {
   text: string;
 }

    const withText = <P extends InterfaceToOmit>(Component: React.ComponentType<P>): React.ComponentClass<Omit<P, keyof InterfaceToOmit>> => {
      // tslint:disable-next-line:max-classes-per-file
      class MyHocClass extends React.Component<Omit<P, keyof InterfaceToOmit>> {
        public render() {
          return <Component text={'what ever your HOC component waht to pass here'} {...this.props as P} />;
        }
      }

      return MyHocClass;
    };

export default withText

您需要返回另一个组件,该组件将省略道具。因此,当您使用 withText 时,它将成为仅包含您不想在 HOC 组件中传递的这些道具的组件。在这个例子中,它的 InterfaceToOmit

所以你的组件仍然有所有的道具

type propsToMyComponent = {
  anything: string;
} & InterfaceToOmit;

const testComponent = (props: propsToMyComponent) => {
  return <div>asd</div>;
};

然后像使用它

 const WithTextComponent = withText<propsToMyComponent>(testComponent);

现在你只能用一个道具来调用它

<WithTextComponent anything={''} />; // no error
于 2019-07-19T12:32:51.057 回答