Check if checkbox element is checked in TypeScript

You just need to use a type assertion to tell TypeScript it is an HTMLInputElement:

var element = <HTMLInputElement> document.getElementById("is3dCheckBox");
var isChecked = element.checked;

Update:

Any ideas why var element = document… works but
var element: HTMLInputElement = document… does not?

When you use getElementById the element returned could be any kind of HTML element. For example, it could be a paragraph tag. For this reason, the type definition for this DOM method returns a very general HTMLElement type.

When you try the following:

var element: HTMLInputElement = document.getElementById('is3dCheckBox');

The compiler warns you that the result of getElementById is not an HTMLInputElement, or a sub-type of HTMLInputElement (because it is actually a super-type of the one you want).

When you know the element type, it is perfectly normal to use a type assertion to tell the compiler the type. When you use the Type Assertion, you tell the compiler you know better.

In some cases, the compiler will still warn you when using a type assertion, because it can tell that the assertion is likely to be a mistake – but you can still force it, but widening the type first:

var isChecked = (<HTMLInputElement><any>myString).checked;

The string variable is widened to the any type, before asserting the HTMLInputElement. Hopefully you won’t need to use this kind of type assertion too often.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)