HTMLInputElement event.target.value outputting a string event though it is a range element (typescript)

Viewed 1760

Issue:

const exampleNumberType: number = 0;
<input type="range" onChange={
   (event: React.ChangeEvent<HTMLInputElement>) => exampleNumberType = event.target.value
}/>

In typescript, the above code will throw an error because the type of event.target.value is 'string', but since it is input from a range event, it should be of type number (since range elements are used for selecting numbers, not strings).

Obviously you could use parseInt() or something similar to convert the value and make it conform to the type that you will need, but there is a more elegant solution (see answer below)...

1 Answers

You could convert the event.target.value string to a number using standard javascript methods, but I think I found a more elegant solution:

My Answer:

Thanks to this documentation I discovered is that there are methods of the 'event.target' object which will return the value as either a number or, if you wanted it, as a Date...

event.target.valueAsNumber

event.target.valueAsDate

So the new, code, with no type errors will look like this:

const exampleNumberType: number = 0;
<input type="range" onChange={
   (event: React.ChangeEvent<HTMLInputElement>) => exampleNumberType = event.target.valueAsNumber
}/>
Related