首页 > 解决方案 > 如何为 React 的“withProps”函数正确定义类型?

问题描述

这是我所拥有的:

export function withProps<P,U extends Partial<P>>(component: React.ComponentType<P>, defaultProps: U): React.FunctionComponent<P & U> {
    return props => React.createElement(component, {...defaultProps, ...props});
}

这是我的使用尝试:

a不应该是必需的Comp2

我尝试将定义更新为

React.FunctionComponent<Omit<P,keyof U>>

但它也不喜欢这样:

我认为正确的输出道具是Omit<P,keyof U> & U. 即,我们删除所有默认道具,然后将它们作为部分(全部可选)添加回来,但我不知道如何让它工作。

在这里试试:https ://codesandbox.io/s/crazy-monad-pzbve

标签: reactjstypescript

解决方案


这有点棘手。为了实现提供的属性的分离,组合类型的声明需要像这样更改:TProps & TDefaultProps. 这种组合类型还需要由 的主要参数Omit。在类型 TPropsTDefaultProps分离之后,它们将没有任何共同的属性。因此,不可能将两个值都分配defaultPropsprops同一个对象。因此,至少as any需要一个。

function withProps<TProps, TDefaultProps>
  (component: React.ComponentType<TProps & TDefaultProps>, defaultProps: TDefaultProps):
     React.FC<Omit<TProps & TDefaultProps, keyof TDefaultProps>> {
       return props => React.createElement(component, { ...defaultProps as any, ...props});
}


推荐阅读