0

On my component I use a custom component for displaying numbers- I need onChange to get the input value, I have tried the below but I get a type error:

Type '(event: any) => void' is not assignable to type '() => void'.ts(2322)

export default function Test({param}) {

  const onChange = key => event => {
    const value = parseInt(event.target.value.replace(/[^0-9]/g, ''))
    const x = {...param.x}
    x.y[key] = value

    setX(param => ({
      ...param,
      payment: x
    }))
  }

  return (
    <>
      <NumberListItem
        label="test"
        value={(param.payment)}
        onChange={onChange('payment')}
        inputProps={{decimalScale: 0, suffix: ' %'}}
      />
    </>
  )
}

NumberListItem component:

export default function NumberListItem({
  value = '',
  onChange = () => {},
  ...rest
}) {
  return (
    <ListItem>
      <NumberField
        value={value}
        onChange={onChange}
        {...rest}
      />
    </ListItem>
  )
}

NumberField component:

export default function NumberField(props: TextFieldProps & NumberFormatProps) {
  return (
    <TextField
      {...props}
      InputProps={{
        inputComponent: NumberFormatCustom
      }}
    />
  )
}
5
  • 1
    change onChange = () => {} to onChange = (e: any) => {} Commented Jun 15, 2020 at 21:09
  • @BeHappy But then I'm getting a 'e' is defined but never used error Commented Jun 16, 2020 at 8:03
  • Where did you do that? What I said, is just set prop type. Commented Jun 16, 2020 at 8:13
  • @BeHappy I changed the onChange = () => {} on NumberListItem to onChange = (e: any) => {} Commented Jun 16, 2020 at 8:16
  • See my answer.. Commented Jun 16, 2020 at 8:32

1 Answer 1

1

You should set prop type:

export interface NumberListItemProps {
  value: string;
  onChange: (e:any) => {};
  [props: string]: any;
}
export default function NumberListItem({
  value = '',
  onChange,
  ...rest
}: NumberListItemProps) {
  return (
    <ListItem>
      <NumberField
        value={value}
        onChange={onChange}
        {...rest}
      />
    </ListItem>
  )
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting a type error: Type '(event: any) => void' is not assignable to type '(e: any) => {}'. Type 'void' is not assignable to type '{}' If I change onChange: (e: any) => {} to ` onChange: (e: any) => void` the onChange param won't be optional anymore, how can I keep it optional?
Would you share your NumberField component?
You have to onChange?: (e:any) => {} to make onChange optional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.