0
votes

I am new to typescript, need guidance on writing type for event handler. I am using material ui Accordion in my component, and calling handler from container. So I need to specify the type of handleChange in my component interface.

Inside component :

<Accordion
        square
        expanded={expanded === 'panel1'}
        onChange={handleChange('panel1')}
>Content</Accordion>

Inside container:

   const handleChange = (panelName: string) => (event, isExpanded: boolean) =>  {
    setExpanded(isExpanded ? panelName : false)
  }

(JSX attribute) AccordionProps.onChange?: ((event: React.ChangeEvent<{}>, expanded: boolean) => void) | undefined

Error : Type 'void' is not assignable to type '((event: ChangeEvent<{}>, expanded: boolean) => void) | undefined'.

Question: What should be specified as a Type for handleChange?

interface Props {
  expanded: string
  handleChange: ???
}
2

2 Answers

0
votes

Your handleChange is a function that returns a function that returns void (it just sets a component state).

Anyway, I guess that Props.handleChange is actually Props.onChange (if it is the Props of Accordion). Anyway, that props signature should be (event: React.ChangeEvent<{}>, expanded: boolean) => void I guess (as the compiler tells you).

So something like this:

interface Props {
    expanded: string;
    onChange(event: React.ChangeEvent<{}>, expanded: boolean): void;
    // or
    onChange: (event: React.ChangeEvent<{}>, expanded: boolean) => void;
}

I hope this is what you need. 😉

0
votes

I got this working, after putting interface type as below,

interface Props {
  expanded: string | boolean
  handleChange: (
    panel: string,
  ) => (event: React.ChangeEvent<unknown>, expanded: boolean) => void
}

Container call:

const handleChange = (panel: string) => (
    event: React.ChangeEvent<unknown>,
    isExpanded: boolean,
  ) => {
    setExpanded(isExpanded ? panel : false)
  }

I was confused due to curried function, but I am not sure, using Type - 'unknown' is the best practice.