In Javascript, it is a pretty common task to get the value of an HTML element to either watch or update that value. With that in mind, it is easy to imagine why that should be simple enough to accomplish in Typescript as well and, for the most part, you would be correct in assuming so. That being said, there are always a few pitfalls in Typescript and one such issue you may run into is the Property 'value' does not exist on type HTMLElement
error.
Normally you would use document.getElementById()
to retrieve an HTML element and then .value
to retrieve its value and, in Typescript, that is still the case. But you may notice that when you try this you run into the aforementioned error. For example given the following HTML:
<div>
<input id="myInput" defaultValue="test" />
</div>
Code language: HTML, XML (xml)
With the following Typescript:
const value = document.getElementById("myInput").value;
Code language: JavaScript (javascript)
You would run into the error. The reason for this is that document.getElemetById()
has a return value of HTMLElement | null
. As a type, HTMLElement
does not actually have a value property and null
is, well, null. So either way there is no value as far as Typescript is concerned. Fortunately, there is a simple trick to resolve this error.
Using the above example, you can just use a type assertion to tell the Typescript compiler what type you are expecting from the method you are using. Type assertions are implemented with either arrow bracket syntax or the as
keyword syntax as shown in the example below. In this case, since the element is an input, we can use HTMLInputElement | null
to ensure we can use the value or handle the case of the element being null
.
// arrow bracket syntax
const value = (<HTMLInputElement | null>document.getElementById("myInput"))?.value;
Code language: PHP (php)
// 'as' syntax
const value = (document.getElementById("myInput") as HTMLInputElement | null)?.value;
Code language: JavaScript (javascript)
In both examples, notice the use of the optional chaining operator. This allows you to safely access the value
property by just returning null
if the element itself is null
or undefined
. This would be essentially equivalent to using an if
/ else
statement.
Typescript definitely has a few caveats and pitfalls but is still worthwhile in many cases. With practice (and helpful guides like this!) you’ll be well on your way to proficiency in this version of Javascript. Happy Coding!
Helped me solve it, thanks !