Icemanind Icemanind - 1 year ago 137
Javascript Question

Typescript throwing an error on valueAsDate

I have the following Javascript code:

var now = new Date();
now.setDate(now.getDate() + 7);
document.getElementById('txtCreateGroupExpirationDate').valueAsDate = now;

When I throw this code into a TypeScript file, TypeScript complains with the following error:

Property 'valueAsDate' does not exist on type 'HTMLElement'

My Javascript works fine and
is a legal property, as defined by the Mozilla Developer Network. In addition, you can see that this property is defined in the Microsoft Typescript Core.

So why am I getting this error? I am using Typescript 2.0.

Answer Source

valueAsDate is only supported on HTMLInputElement, and TypeScript doesn't know what kind of element txtCreateGroupExpirationDate is. Use a type assertion to change the type of the expression:

(<HTMLInputElement>document.getElementById('txtCreateGroupExpirationDate')).valueAsDate = now;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download