To extend type union props for a React class component, you can use TypeScript's intersection (&) operator. This allows you to merge multiple types together, effectively combining their props into a single type that you can use for your class component.

Here's how you can do it:

  1. Define Prop Types:

    • First, define your different prop types as separate interfaces.
    interface CommonProps { // Define common props here className?: string; } interface ComponentAProps { // Props specific to ComponentA propA: string; } interface ComponentBProps { // Props specific to ComponentB propB: number; }
  2. Create Your Class Component:

    • Next, create your class component and use the intersection (&) operator to merge the common props with the specific props for ComponentA or ComponentB.
    import React, { Component } from 'react'; interface MyComponentProps extends CommonProps, ComponentAProps { // Using intersection to combine the props } class MyComponent extends Component<MyComponentProps> { render() { // Access props as usual const { className, propA, propB } = this.props; return ( <div className={className}> <p>Component A Prop: {propA}</p> <p>Component B Prop: {propB}</p> </div> ); } }
  3. Using the Component:

    • Now you can use your MyComponent class component, passing the required props based on the combination of ComponentAProps and ComponentBProps.
    // Example usage <MyComponent propA="Hello" propB={42} className="custom-class" />

By extending the type union props using the intersection operator, you can create more flexible and reusable components that accept a combination of different props. This pattern is particularly useful when you have multiple related components that share some common props but have unique additional props.

Have questions or queries?
Get in Touch