Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle number input in typescript?

this is how a regular input field would be handled in react/typescript where value is type string:

const [value, onChange] = useState<string>('');

const onChange = (e: ChangeEvent<HTMLInputElement>) {
  setValue(e.target.value);
}

return (
  <input
    value={value}
    onChange={onChange}
  />
);

But I'm having trouble where my input is of type number:

const [value, onChange] = useState<number>();

const onChange = (e: ChangeEvent<HTMLInputElement>) {
  // type error
  setValue(e.target.value);
}

return (
  <input
    type="number"
    value={value}
    onChange={onChange}
  />
);

in this case, value is of type number, input is of type number (so hypothetically e.target.value should always be of type number. However according to typescript, event.target.value is always a string. I can cast it to number ie.

const onChange = (e: ChangeEvent<HTMLInputElement>) {
  setValue(Number(e.target.value));
}

but now if some number is typed in and the user backspaces it to make it empty, the value changes to 0 - the field can never be empty.

keeping value as string and then casting it to number on save is not a viable solution

something i'm temporarily doing is making e.target.value as any:

const onChange = (e: ChangeEvent<HTMLInputElement>) {
  setValue(e.target.value as any);
}

which works great but am I missing something to keep this type safe?

like image 392
james Avatar asked Apr 07 '20 00:04

james


People also ask

How do you put numbers in TypeScript?

this is how a regular input field would be handled in react/typescript where value is type string: const [value, onChange] = useState<string>(''); const onChange = (e: ChangeEvent<HTMLInputElement>) { setValue(e. target. value); } return ( <input value={value} onChange={onChange} /> );

How do you read input values in TypeScript?

You can get the value of an input in TypeScript.getElementById("myValue")). value); or let num : number = parseFloat((<HTMLInputElement>document. getElementById("myValue")). value);

How do I allow only input field numbers?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.


1 Answers

In general, you'll want to make your variable a string for everything to work well.

Then when you want to use it as a number, convert it at that point. You can easily convert it to a number using something like +value or parseFloat(value)

The input uses a string type for a reason. And this way you keep the typesafety that typescript provides.

like image 142
Zachary Haber Avatar answered Oct 23 '22 11:10

Zachary Haber