Istvan Orban
Istvan Orban

Reputation: 1685

ReactTS extend type by dynamic Component Props?

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

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions