Search code examples
reactjstypescriptjsxreact-tsx

Optional JSX Props In a TSX/JSX Project


I have a React project that I'm converting from JS to TS. An issue I'm running into is that TSX React is assuming that all properties defined in a functional component are required props.

// ComponentA.tsx
class ComponentA extends React.Component<any, any> {
  render() {
    /* Type '{ equalWidth: true; children: Element[]; }' is not assignable to type '{ children: any; className: any; equalWidth: any; }'.
     * Property 'className' is missing in type '{ equalWidth: true; children: Element[]; }'.' */
    return <ComponentB equalWidth />
  }
}

and

// ComponentB.js
const ComponentB = ({ children, className, equalWidth }) => {
  return (...)
}

is there a way to signal to TS that JSX component props are all optional?


Solution

  • One simplest option will be setting a default value for your optional props. As an example, if className is optional you can change your ComponentB.js to something like this.

    const ComponentB = ({ children, className="", equalWidth }) => {
      return (...)
    }
    

    Also if you deconstruct your props in the function body instead of the signature TS will not complain about typings.

    const ComponentB = (props) => {
      const { children, className, equalWidth } = props;
      return (...)
    }