Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct TypeScript object with HTML input values?

Tags:

typescript

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 ?

like image 493
Anmol Gupta Avatar asked Aug 10 '15 14:08

Anmol Gupta


2 Answers

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.

like image 141
Anmol Gupta Avatar answered Oct 29 '22 02:10

Anmol Gupta


let value : number = parseFloat((<HTMLInputElement>document.getElementById("myValue")).value);
let unit : string = (<HTMLInputElement>document.getElementById("myUnit")).value; 

myObject: MyObject = new MyObject(value, unit);

It could also be written like this:

let value : number = parseFloat((document.getElementById("myValue") as HTMLInputElement).value);
let unit : string = (document.getElementById("myUnit") as HTMLInputElement).value; 

myObject: MyObject = new MyObject(value, unit);

Note that I have not used var but instead let, which gives you better control over your code.

Note: using as or direct casting via <> is up to you. Personally I don't know typescript that well to know the specific difference. My guess is that using 'as' does an extra check just like C#, but how it does error handling in case it is not an HTMLInputElement, I don't know that. (maybe somebody can comment on that).

In the typescript tutorial they also use "as": http://www.typescriptlang.org/docs/handbook/asp-net-4.html

like image 36
juFo Avatar answered Oct 29 '22 00:10

juFo