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?
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} /> );
You can get the value of an input in TypeScript.getElementById("myValue")). value); or let num : number = parseFloat((<HTMLInputElement>document. getElementById("myValue")). value);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With