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

Use generics with setstate in react js and typescript return string instead of number

I am trying to setState onChange event by passing the type of setstate hook.
here is my setState:

const [payer, setPayer] = useState<Number>(0);

and here is my radio setter:

const radioSetter = <T,>(
    e: React.FormEvent<HTMLInputElement>,
    setter: React.Dispatch<React.SetStateAction<T>>
  ) => {
    console.log(typeof (e.currentTarget.value as T));
    setter(e.currentTarget.value as T);
  };

and this is my input:

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

<input
                      type="radio"
                      name="payer"
                      value={0}
                      checked={payer === 0}
                      onChange={(event) => radioSetter<Number>(event, setPayer)}
                    />

the consol log of radioSetter function is string instead of number.
how can i pass the type of setState when calling radioSetter function in onchange event?

>Solution :

First off, use number instead of Number (see why here):

const [payer, setPayer] = useState<number>(0);

Then use valueAsNumber instead of value, or convert the string to a number,

onChange={(event) => setPayer(event.target.valueAsNumber)}
onChange={(event) => setPayer(Number(event.target.value))}
onChange={(event) => setPayer(+event.target.value)}

I wouldn’t use a function like radioSetter since there is no way you can know what type you are supposed to pass to the setter at runtime, and it doesn’t seem like it’s doing much anyways.

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