[英]React & Typescript component props type for `Component`
I have the following HOC in React: 我在React中有以下HOC:
`restricted` prop
const ConditionalSwitch = ({component: Component, showIfTrue, ...rest}) => (
showIfTrue
? <Component {...rest}/>
: null
);
How do I define the props so that Typescript will be happy with it? 如何定义道具,以便Typescript满意呢?
{component: Component, showIfTrue, ...rest}
I tried 我试过了
export interface CSProps {
component: any,
showIfTrue: boolean
}
How do I handle the ...rest
here? 我该如何处理
...rest
?
If you want to preserve type safety, you need to make ConditionalSwitch
generic and have it infer the full props passed to the component based on the actual value of Component
. 如果要保留类型安全,则需要使
ConditionalSwitch
泛型,并使其根据Component
的实际值推断传递给组件的完整属性。 This will ensure that the client of ConditionalSwitch
will pass in all the required properties of the used component. 这将确保
ConditionalSwitch
的客户端将传入所使用组件的所有必需属性。 To do this we use the approach described here : 为此,我们使用此处描述的方法:
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
When passing the rest
to the component we do need to use a type assertion because typescript is not able to figure out that { Component: C, showIfTrue: boolean} & React.ComponentProps<C>
minus Component
and showIfTrue
is just React.ComponentProps<C>
but you can't have it all :) 当将
rest
传递给组件时,我们确实需要使用类型断言,因为类型{ Component: C, showIfTrue: boolean} & React.ComponentProps<C>
无法找出{ Component: C, showIfTrue: boolean} & React.ComponentProps<C>
减去Component
而showIfTrue
只是React.ComponentProps<C>
但你不能拥有全部:)
Try this: 尝试这个:
export interface CSProps {
component: any;
showIfTrue: boolean;
[key: string]: any;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.