我在React中有以下HOC:
`restricted` prop
const ConditionalSwitch = ({component: Component, showIfTrue, ...rest}) => (
showIfTrue
? <Component {...rest}/>
: null
);
如何定义道具,以便Typescript满意呢?
{component: Component, showIfTrue, ...rest}
我试过了
export interface CSProps {
component: any,
showIfTrue: boolean
}
我该如何处理...rest
?
如果要保留类型安全性,则需要将ConditionalSwitch
泛型设为通用,并根据的实际值推断传递给组件的完整属性Component
。这将确保的客户端ConditionalSwitch
将传入所用组件的所有必需属性。为此,我们使用此处描述的方法:
const ConditionalSwitch = <C extends React.ComponentType<any>>({ Component, showIfTrue, ...rest}: { Component: C, showIfTrue: boolean} & React.ComponentProps<C> ) => (
showIfTrue
? <Component {...(rest as any) }/>
: null
);
function TestComp({ title, text}: {title: string, text: string}) {
return null!;
}
let e = <ConditionalSwitch Component={TestComp} showIfTrue={true} title="aa" text="aa" /> // title and text are checked
当将传递rest
给组件时,我们确实需要使用类型断言,因为typescript不能找出{ Component: C, showIfTrue: boolean} & React.ComponentProps<C>
负号Component
,showIfTrue
而只是React.ComponentProps<C>
但您不能拥有全部:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句