[英]Infer second parameter type from first parameter type in typescript react
I'm trying to make a utility function that creates a new react component from a different react component that accepts different set of props.我正在尝试制作一个实用程序 function ,它从接受不同道具集的不同反应组件创建一个新的反应组件。 I have following code:我有以下代码:
function makeNewComponent(
OldComponent: React.ComponentType<any>,
prepareProps: () => typeof OldComponent.propTypes
): React.ComponentType {
return function NewComponent() {
const oldComponentProps = prepareProps();
return <OldComponent {...oldComponentProps} />;
};
}
But it's not inferring return type of the prepareProps
function properly.但它没有正确推断prepareProps
function 的返回类型。 For example if I use the makeNewComponent
function like this:例如,如果我像这样使用makeNewComponent
function:
const OldComponent: React.FC<{ num1: number }> = () => {
return <div>hello</div>;
};
const NewComponent = makeNewComponent(OldComponent, () => ({}));
Typescript infers the return type of the prepareProps
function as Typescript 推断prepareProps
function 的返回类型为
prepareProps: () => React.WeakValidationMap<{}> | undefined
but I need it to be like this:但我需要它是这样的:
prepareProps: () => { num1: number; }
I have tried different things but I can't get it to work.我尝试了不同的东西,但我无法让它发挥作用。 I also tried nesting some functions like following:我还尝试嵌套一些函数,如下所示:
function makeNewComponent2(OldComponent: React.ComponentType<any>) {
return function (prepareProps: () => typeof OldComponent.propTypes) {
return function NewComponent() {
const oldComponentProps = prepareProps();
return <OldComponent {...oldComponentProps} />;
};
};
}
But it's still not working.但它仍然无法正常工作。 Any solution?有什么解决办法吗?
The following would do the trick:以下方法可以解决问题:
type ExtractPropTypes<T> = T extends React.WeakValidationMap<infer P> ? P : never;
function makeNewComponent<T extends React.ComponentType<any>>(
Component: T,
prepareProps: () => ExtractPropTypes<T['propTypes']>
): React.ComponentType {
return function NewComponent() {
const props = prepareProps();
return <Component {...props} />;
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.