Squiggs.
Squiggs.

Reputation: 4474

Typescript, how to handle spread operators inside interface

I currently have a react component that looks like this - notice the spread operator which operates on ...other and is passed on further down the component.

interface ButtonProps {
  colourMode: string;
  regular: boolean;
  buttonText: string;
  disabled?: boolean;
  iconSize?: string;
  iconLeft?: React.ReactNode;
  iconRight?: React.ReactNode;
}

const LowProButton = (props: ButtonProps) => {
  const {
    colourMode,
    buttonText,
    disabled,
    iconSize,
    iconLeft,
    iconRight,
    ...other
  } = props;

When I try to pass any additional parameter to this button i.e: the onClick in the consumer, it complains that the props are not assignable to type 'IntrinsicAttributes & ButtonProps' - how do I fix the interface to allow any prop to be passed safely through whilst keeping the strongly typed elements within the interface? To be clear, I want to pass any prop I want to the component, i.e. the onClick or anything else I wish, whilst keeping the colourMode: string etc.

<LowProButton
        iconSize="14"
        regular={false}
        iconLeft={<RestartAltIcon />}
        colourMode="secondary"
        buttonText="Detailed"
        onClick={props.performClick}
      ></LowProButton>

Upvotes: 0

Views: 92

Answers (1)

leo
leo

Reputation: 111

What exactly do you want to achieve with other? If you want to have all the usual html button properties you then need to extend your interface to allow it so something like

interface ButtonProps extends HTMLButtonElement {
  colourMode: string;
  regular: boolean;
  buttonText: string;
  disabled?: boolean;
  iconSize?: string;
  iconLeft?: React.ReactNode;
  iconRight?: React.ReactNode;
}

Upvotes: 1

Related Questions