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 ?
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.
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
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