What is the correct way to declare this function prop?

Viewed 125

Hi I am new to typescript & I have 2 component in my project, Input Dialog & Setting menu component. I am using inputDialog inside the settingmenu component

my input dialog component is like this

interface InputDialogContentProps {
  inputLabel: string;
  inputType: string;
  onChange?: any;
}

export default function InputDialogContent(props: InputDialogContentProps) {
  const classes = inputDialogStyle();

  return (
    <DialogContent className={classes.dialogContentPlacement}>
      <TextField
        autoFocus
        className={classes.textFieldStyle}
        margin="dense"
        id="name"
        label={props.inputLabel}
        type={props.inputType}
        onChange={props.onChange}
        fullWidth
      />
    </DialogContent>

Please take note that I declare on change as any in this component.

here is my setting menu document.

<InputDialogContent
            inputLabel="Email Address"
            inputType="email"
            onChange={onInputChange}
          />

function onInputChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
    setEnableLoginButton(isValidEmail(e.target.value));
  }

As you can see i am using onChange to keep track of the changes inside the html text area. So Rather than any What is the right way to declare this Onchange inside the inputDialog Component

1 Answers

It would be:

interface InputDialogContentProps {
  inputLabel: string;
  inputType: string;
  onChange?: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
//           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

That's a function that accepts a single parameter of type React.ChangeEvent<HTMLTextAreaElement> and doesn't return anything. The general form is:

(parameters) => returnType;

More in the TypeScript handbook.

Related