Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react typescript type based on other type

I have a component like this

type inputProps = {
  value: string | number | boolean
  onChange: (arg: string | number | boolean) => void
}

const Input = ({value, onChange}: inputProps) => {
  return <div />
}

const OtherComponent = () => {
  const [value, setValue] = React.useState(5)

  // onChange type not compatible
  return <Input  value={value} onChange={setValue} />
}

const AnotherComponent = () => {
  const [value, setValue] = React.useState('Hey')

  // onChange type not compatible
  return <Input  value={value} onChange={setValue} />
}

playground link

Is it possible to make the arg of the onChange function dependent on the value?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes. It is possible using Generics:

type inputProps<T> = {
  value: T;
  onChange: (arg: T) => void;
};

const Input = <T,>({ value, onChange }: inputProps<T>) => {
  return <div />;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading