Reputation: 1685
Is it possible to have a React component what can find out dynamically what props its got?
Example:
type BaseType = {
baseProp?: ...
as?: ...
}
type Extended = {
extendedProp?: ...
}
<Base /> // expected props => { baseProp }
<Base as={ExtendedComponent} extendedProp={...} /> // expected props => { baseProp, extendedProp }
Upvotes: 0
Views: 567
Reputation: 249666
Taking a cue from this answer we can, using intersections first infer the type of the props from as
and then use those props to validate any extra properties:
type BaseType = {
baseProp?: number
}
type Extended = {
extendedProp?: string
}
declare const ExtendedComponent: React.FC<Extended>
function Base<T = {}>(p: BaseType & { as? : React.ComponentType<T>} & T): React.ReactElement{
if(p.as) {
const Child = p.as;
return <div>{p.baseProp}<Child {...p as T}></Child></div>
}else {
return <div>{p.baseProp}</div>
}
}
let s = <Base /> // expected props => { baseProp }
let a = <Base as={ExtendedComponent} extendedProp="a" />
Upvotes: 1