Nisarg Kudgunti
Nisarg Kudgunti

Reputation: 101

How to get the value of time element in Typescript?

I have a time input element in HTML and I want its value as a number in Typescript. In Javascript we can do that by var time = document.getElementById("time").valueAsNumber;

But in Typescript it is throwing an error that Property 'valueAsNumber' does not exist on type 'HTMLTimeElement' after I wrote this code,

var time = <HTMLTimeElement>document.getElementById("time").valueAsNumber;

What do I do?

Upvotes: 1

Views: 1224

Answers (2)

Parzh from Ukraine
Parzh from Ukraine

Reputation: 9903

Well, HTMLTimeElement values (for <time> tags) actually don't have valueAsNumber properties, you can believe TypeScript compiler on that. It seems like you really need to use HTMLInputElement interface (for <input type="time"> elements) instead:

var time = (<HTMLInputElement> document.getElementById("time")).valueAsNumber;

Another issue is that you have fallen to TypeScript's operator precendence trap: the property accessor operator (object.prop) has higher priority over type cast operator (<Type> value). Your expression therefore reads as this:

var time = <HTMLTimeElement> (document.getElementById("time").valueAsNumber);

… whereas you need this:

var time = (<HTMLTimeElement> document.getElementById("time")).valueAsNumber;

(See https://stackoverflow.com/a/28316948/4554883 for details.)

Upvotes: 1

0Valt
0Valt

Reputation: 10365

You made an incorrect assumption:

That <input type="time" /> translates to an HTMLTimeElement interface. The latter represents a special element with the tag <time> used in semantic markup containing machine-readable date & time as its value under the dateTime property (see the MDN reference).

What you needed instead was the HTMLInputElement interface which is shared by all <input> elements, the valueAsNumber will be present on the interface:

const { valueAsNumber } = <HTMLInputElement>(document.getElementById("time")); //OK, valueAsNumber is number

Playground

Upvotes: 1

Related Questions