具有所需道具的 HOC 打字稿
Typescript for HOC with required props
我有一个组件 MyComponent
接受一些道具,其中一个是可选的:
type Props = {
a: string;
b: number;
c?: string;
}
我写了一个高阶组件,在属性c
的基础上增加了一些功能。为了让它有意义,我决定在 HOC 上设置 属性 c
:
type CProps = Props & {
c: string;
};
export const withC = (WrappedComponent: ComponentType<CProps>) => {
const WithC = (props: CProps) => {
///...
}
return WithC;
};
现在,当我尝试这样做时,打字稿正在抱怨:
const MyComponentC = withC(MyComponent);
说 属性 c
在 withC
上是必需的,但在 MyComponent
上不是。
我该如何绕过这个,最好不改变 MyComponent
的道具类型?
WithC 将始终 运行 即使您没有通过 c prop。所以如果传递了 c prop,你必须调用该函数
type CProps = Props & {
c: string;
};
export const withC = (WrappedComponent: ComponentType<Props>) => {
const WithC = (props: CProps) => {
///...
}
return WithC;
};
WrappedComponent
应该还没有必需的 c
,但是 WithC
应该有。
我有一个组件 MyComponent
接受一些道具,其中一个是可选的:
type Props = {
a: string;
b: number;
c?: string;
}
我写了一个高阶组件,在属性c
的基础上增加了一些功能。为了让它有意义,我决定在 HOC 上设置 属性 c
:
type CProps = Props & {
c: string;
};
export const withC = (WrappedComponent: ComponentType<CProps>) => {
const WithC = (props: CProps) => {
///...
}
return WithC;
};
现在,当我尝试这样做时,打字稿正在抱怨:
const MyComponentC = withC(MyComponent);
说 属性 c
在 withC
上是必需的,但在 MyComponent
上不是。
我该如何绕过这个,最好不改变 MyComponent
的道具类型?
WithC 将始终 运行 即使您没有通过 c prop。所以如果传递了 c prop,你必须调用该函数
type CProps = Props & {
c: string;
};
export const withC = (WrappedComponent: ComponentType<Props>) => {
const WithC = (props: CProps) => {
///...
}
return WithC;
};
WrappedComponent
应该还没有必需的 c
,但是 WithC
应该有。