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:

                      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(}
onChange={(event) => setPayer(Number(}
onChange={(event) => setPayer(}

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.

Leave a Reply