我用 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' 属性
链接到代码框 ->这里