Anmol Gupta Anmol Gupta - 1 year ago 238
TypeScript Question

How to construct TypeScript object with HTML input values?

This should be very basic but I am unable to get through it.

I have a class like:

class MyObject {
value: number;
unit: string;

constructor(value: number, unit: string){
this.value = value;
this.unit = unit;

Then in HTML,

<input id="myValue" type="number"></input>
<input id="myUnit" type="text"></input>

I want to create an Object of "MyObject" class using myValue and myUnit. How do I do that ?

Something like:

var value = document.getElementById("myValue");
var unit = document.getElementById("myUnit");
myObject: MyObject = new MyObject(value, unit);

Unable to do it the above way. What's the way to go about with this ?

Answer Source

Here is the final answer which works in TypeScript (Reference for casting HTMLElement to HTMLInputElement: The property 'value' does not exist on value of type 'HTMLElement' )

var value = parseFloat((<HTMLInputElement>document.getElementById("myValue")).value);
var unit = (<HTMLInputElement>document.getElementById("myUnit")).value; 
myObject: MyObject = new MyObject(value, unit);

It was important to cast HTMLElement to HTMLInputElement, otherwise 'value' property doesn't exist for HTMLElement in TypeScript and TypeScript compiler will show error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download